<?php

namespace KupShop\AutomationConfiguratorBundle\Controller;

use KupShop\AdminBundle\AdminRequiredControllerInterface;
use KupShop\AutomationConfiguratorBundle\Configurator\ConfigurationSaver;
use KupShop\AutomationConfiguratorBundle\Util\AutomationConfiguratorLocator;
use KupShop\KupShopBundle\Util\System\PathFinder;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Annotation\Route;

class BuilderController extends AbstractController implements AdminRequiredControllerInterface
{
    /**
     * @return \Symfony\Component\HttpFoundation\Response
     *
     * @Route("/_contextBuilder/autocompleteTrigger/{configId}", defaults={"searchValue":""})
     * @Route("/_contextBuilder/autocompleteTrigger/{configId}/{searchValue}")
     *
     * @throws \Exception
     */
    public function testAutocompleteAction(
        Request $request,
        ConfigurationSaver $saveConfiguration,
        AutomationConfiguratorLocator $automationConfiguratorLocator,
        $configId,
        $searchValue,
    ) {
        $configuration = $saveConfiguration->retrieve($configId);

        $contextProvider = $automationConfiguratorLocator->getContextProvider($configuration->getContext());

        $responseData = $contextProvider->getTestAutocompleteData($searchValue);

        $response = new JsonResponse(['values' => $responseData]);

        return $response;
    }

    /**
     * @return \Symfony\Component\HttpFoundation\Response
     *
     * @Route("/_contextBuilder/admin/")
     *
     * @throws \Exception
     */
    public function testAction(
        Request $request,
        PathFinder $pathFinder,
    ) {
        return $this->redirectToRoute('kupshop_admin_admin_launch', $request->query->all(), 307);
    }
}
