<?php

namespace idoit\Module\SyneticsFlows\Controller;

use idoit\Module\SyneticsFlows\Auth;
use idoit\Module\SyneticsFlows\Controller\Response\ArrayResponse;
use idoit\Module\SyneticsFlows\Controller\Response\MalformedResponse;
use idoit\Module\SyneticsFlows\Controller\Response\NotFoundResponse;
use idoit\Module\SyneticsFlows\Filter\AttributeFilter;
use idoit\Module\SyneticsFlows\Model\AttributeDao;
use idoit\Module\SyneticsFlows\Validation\ValidationMessage;
use isys_auth;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;

class AttributeController extends BaseController
{
    /**
     * @var AttributeDao|null
     */
    private ?AttributeDao $attributeDao = null;

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

    /**
     * @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'));
        $attributeFilter = AttributeFilter::fromParams($request->get('params'));

        return new ArrayResponse(
            $this->getDao()->getData($attributeFilter, $search),
            $this->getDao()->getCount($attributeFilter),
        );
    }

    /**
     * @param string $id
     *
     * @return JsonResponse
     * @throws \Exception
     */
    public function get(string $id): JsonResponse
    {
        if (!Auth::instance()->manageFlows(isys_auth::VIEW)) {
            return JSONResponseFactory::accessDenied();
        }

        if (strpos($id, '.') === false) {
            return new MalformedResponse($this->translateErrorMessages([
                new ValidationMessage(['id'], 'LC__MODULE__SYNETICS_FLOWS__ATTRIBUTE_INVALID_ERROR')
            ]));
        }

        $result = $this->getDao()->get($id);
        if ($result === null) {
            return new NotFoundResponse('Attribute');
        }

        return new JsonResponse($result);
    }
}
