<?php

namespace idoit\Module\SyneticsJdisc\Controller;

use idoit\Module\SyneticsJdisc\Controller\Response\NotFoundResponse;
use idoit\Module\SyneticsJdisc\Model\DeviceListColumnsDao;
use isys_application;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;

class DeviceListColumnsController extends AbstractController
{
    private ?DeviceListColumnsDao $dao = null;

    /**
     * @return DeviceListColumnsDao
     * @throws \Exception
     */
    private function getDao(): DeviceListColumnsDao
    {
        if (null === $this->dao) {
            $this->dao = isys_application::instance()->container->get('idoit.jdisc.device-list.columns.dao');
        }
        return $this->dao;
    }

    /**
     * @param Request $request
     * @return Response
     */
    public function get(Request $request): Response
    {
        $serverId = $request->get('serverId');

        $dao = $this->getDao();
        if (!$dao->init($serverId)) {
            return new NotFoundResponse('DiscoveryServer');
        }

        $response = new JsonResponse();
        try {
            $response->setData($dao->get());
        } catch (\Throwable $e) {
            $response->setData(['error' => $e->getMessage()]);
            $response->setStatusCode(Response::HTTP_INTERNAL_SERVER_ERROR);
        }

        return $response;
    }

    /**
     * @param Request $request
     * @return Response
     */
    public function hide(Request $request): Response
    {
        $response = new JsonResponse();
        $serverId = $request->get('serverId');

        $dao = $this->getDao();
        $dao->init($serverId);

        try {
            $response->setData(
                [
                    'hidden' => $dao->hide(
                        json_decode($request->get('columns'), true) ?? []
                    ),
                ]
            );
        } catch (\Throwable $e) {
            $response->setData(['error' => $e->getMessage()]);
            $response->setStatusCode(Response::HTTP_INTERNAL_SERVER_ERROR);
        }

        return $response;
    }
}
