<?php


namespace AutoAdmin\Bundle\Admin\Controller\Admin;


use AutoAdmin\Bundle\Admin\Configuration\ConfigManager;
use AutoAdmin\Bundle\Content\ContentReference\ContentReferenceResolver;
use AutoAdmin\Bundle\Content\Entity\ContentReference;
use AutoAdmin\Bundle\Content\Model\ContentInterface;
use AutoAdmin\Bundle\Content\Model\TranslatableInterface;
use AutoAdmin\Bundle\Content\Model\TranslationInterface;
use AutoAdmin\Bundle\Content\Repository\AbstractTranslatableContentRepository;
use InvalidArgumentException;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;


class ContentReferenceController extends AbstractAdminController
{
    public function init(
        Request $request,
        ConfigManager $configManager,
        ContentReferenceResolver $resolver
    ): JsonResponse
    {
        $referenceId = $request->get('content_reference_id');
        if (empty($referenceId)) {
            throw new InvalidArgumentException('Invalid "content_reference_id"');
        }

        /** @var AbstractTranslatableContentRepository $repo */
        $repo = $this->entityHelper->getManager()->getRepository(ContentReference::class);

        /** @var ContentReference $reference */
        $reference = $repo->find($referenceId);

        /** @var TranslatableInterface $content */
        $content = $resolver->resolve($reference);

        $entityConfig = $configManager->getEntityConfigByClass(get_class($content));

        return $this->json(
            [
                'content' => [
                    'value' => $content->getId(),
                    'slug' => $entityConfig['slug'],
                    'label' => $content->getCurrentTranslation()->getName() . sprintf(' (#%s)', $content->getId()),
                ],
            ]
        );
    }

    public function search(Request $request, ConfigManager $configManager): JsonResponse
    {
        $contentSlug = $request->get('content_slug');
        $term = $request->get('term');

        if (empty($contentSlug) || empty($term)) {
            throw new InvalidArgumentException('You must at least provide a "content_slug" and a search "term".');
        }

        $config = $configManager->getEntityConfigBySlug($contentSlug);
        if (empty($config)) {
            throw new InvalidArgumentException('Invalid content slug');
        }

        /** @var AbstractTranslatableContentRepository $repo */
        $repo = $this->entityHelper->getManager()->getRepository($config['class']);

        $criteria = [];
        if (!empty($term)) {
            $criteria = [
                '_tr.name LIKE' => '%' . $term . '%',
            ];
        }
        $results = $repo->contentFindBy($criteria);

        $jsonResults = [];
        /** @var ContentInterface|TranslatableInterface $result */
        foreach ($results as $result) {
            /** @var TranslationInterface $translation */
            $translation = $result->getCurrentTranslation();
            if ($translation) {
                $jsonResults[] = [
                    'value' => $result->getId(),
                    'slug' => $contentSlug,
                    'label' => $translation->getName() . sprintf(' (#%s)', $result->getId()),
                ];
            }
        }

        return $this->json(['contents' => $jsonResults]);
    }
}
