<?php

namespace idoit\Module\SyneticsFlows\Controller;

use idoit\Module\SyneticsFlows\Auth;
use idoit\Module\SyneticsFlows\Controller\Response\ArrayResponse;
use idoit\Module\SyneticsFlows\Controller\Response\NotFoundResponse;
use idoit\Module\SyneticsFlows\Model\ObjectTypeDao;
use isys_auth;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;

class ObjectTypeController
{
    /**
     * @var ObjectTypeDao|null
     */
    private ?ObjectTypeDao $objectTypeDao = null;

    /**
     * @return ObjectTypeDao
     * @throws \Exception
     */
    public function getDao(): ObjectTypeDao
    {
        if (!$this->objectTypeDao) {
            $this->objectTypeDao = \isys_application::instance()->container->get('idoit.flows.object-type.dao');
        }
        return $this->objectTypeDao;
    }

    /**
     * @param Request $request
     *
     * @return Response
     * @throws \Exception
     */
    public function find(Request $request): Response
    {
        if (!Auth::instance()->manageFlows(isys_auth::VIEW)) {
            return JSONResponseFactory::accessDenied();
        }

        $search = SearchParams::fromParams($request->get('params'));
        return new ArrayResponse(
            $this->getDao()->getData(null, $search),
            $this->getDao()->getCount(),
        );
    }

    /**
     * @param string $id
     *
     * @return Response
     * @throws \Exception
     */
    public function get(string $id): Response
    {
        if (!Auth::instance()->manageFlows(isys_auth::VIEW)) {
            return JSONResponseFactory::accessDenied();
        }
        $result = $this->getDao()->get($id);
        if ($result === null) {
            return new NotFoundResponse('Object type');
        }
        return new JsonResponse($result);
    }
}
