<?php

namespace idoit\Module\SyneticsFlows\Controller;

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

/**
 * Execution controller
 *
 * @package   idoit\Module\synetics_flows\Controller
 * @copyright synetics
 * @license   https://www.i-doit.com/
 */
class ExecutionController
{
    private ?ExecutionDao $executionDao = null;
    private ?TriggerService $service = null;

    public function find(Request $request): Response
    {
        if (!Auth::instance()->manageFlows(isys_auth::VIEW)) {
            return JSONResponseFactory::accessDenied();
        }

        $search = SearchParams::fromParams($request->get('params'));
        $flowId = $request->get('flowId');


        $condition = null;
        if (is_string($flowId)) {
            $condition = ' AND isys_flow_execution__isys_flow_automation__id = ' . $this->getDao()->convert_sql_text($flowId);
        }

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

    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('Execution');
        }
        return new JsonResponse($result);
    }

    public function perform(string $id): Response
    {
        if (!Auth::instance()->manageFlows(isys_auth::EXECUTE)) {
            return JSONResponseFactory::accessDenied();
        }
        $result = $this->getService()->perform($id);
        return new JsonResponse($result);
    }

    public function getDao(): ExecutionDao
    {
        if (!$this->executionDao) {
            $this->executionDao = \isys_application::instance()->container->get('idoit.flows.execution.dao');
        }
        return $this->executionDao;
    }

    public function getService(): TriggerService
    {
        if (!$this->service) {
            $this->service = \isys_application::instance()->container->get('idoit.flows.trigger');
        }
        return $this->service;
    }
}
