<?php

namespace idoit\Module\SyneticsFlows\Controller;

use idoit\Module\SyneticsFlows\Auth;
use idoit\Module\SyneticsFlows\Controller\Response\ArrayResponse;
use idoit\Module\SyneticsFlows\Controller\Response\AttributeDataIdNotFoundResponse;
use idoit\Module\SyneticsFlows\Controller\Response\MalformedResponse;
use idoit\Module\SyneticsFlows\Controller\Response\NotFoundResponse;
use idoit\Module\SyneticsFlows\Filter\AttributeDataFilter;
use idoit\Module\SyneticsFlows\Filter\AttributeFilter;
use idoit\Module\SyneticsFlows\Model\AttributeDataDao;
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 AttributeDataController
{
    /**
     * @var AttributeDataDao|null
     */
    private ?AttributeDataDao $attributeDataDao = null;

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

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

        if (strpos($id, '.') === false) {
            return new AttributeDataIdNotFoundResponse($id);
        }

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

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

        if (strpos($id, '.') === false) {
            return new AttributeDataIdNotFoundResponse($id);
        }

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