<?php

namespace Comitium5\DesignerBundle\Controller\Search\Suggest;

use Comitium5\DesignerBundle\Entity\Subsite;
use Comitium5\DesignerBundle\Factory\Search\Suggest\SearchQueryObjectFactory;
use Comitium5\DesignerBundle\UseCase\Search\MultiSubSiteSuggestSearchUseCase;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;

/**
 * Class MultiSubSiteSuggestController
 *
 * @author David Carrascosa <david@bab-soft.com>
 * @package Comitium5\DesignerBundle\Controller\Search\Suggest
 */
class MultiSubSiteSuggestController extends Controller
{
    /**
     * @param Request $request
     *
     * @return JsonResponse
     * @throws \Exception
     */
    public function __invoke(Request $request): JsonResponse
    {
        $useCase = new MultiSubSiteSuggestSearchUseCase(
            $this->get('designer.repository.search'),
            SearchQueryObjectFactory::create(
                $request,
                $this->get('designer.provider.locale'),
                $this->selectedSubsites($request)
            ),
            $request->get('labelProperties'),
            $request->get('property')
        );

        return $useCase();
    }

    /**
     * @param Request $request
     *
     * @return array
     * @throws \Exception
     */
    protected function selectedSubsites(Request $request): array
    {
        if ($request->get('subsites')) {
            $selected = [];
            $subSites = $request->get('subsites');
            foreach ($subSites as $subSiteAcronym) {
                $selected[] = (new Subsite())->setAcronym($subSiteAcronym);
            }

            return $selected;
        }

        return $this->get('designer.provider.subsite_multiple')->getSubsites();
    }
}