<?php
/**
 * @author Colinet Julien
 */

namespace CpCreation\VitiCore\Bridge\Symfony\Bundle\ParamConverter;

use CpCreation\VitiCore\Behavior\HasTranslatable;
use Doctrine\ORM\EntityManagerInterface;
use Http\Discovery\Exception\NotFoundException;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\ParamConverter;
use Sensio\Bundle\FrameworkExtraBundle\Request\ParamConverter\ParamConverterInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\Translation\Exception\NotFoundResourceException;

class TranslationParamConverter implements ParamConverterInterface
{

    /**
     * @var EntityManagerInterface
     */
    private $em;

    public function __construct(EntityManagerInterface $em)
    {
        $this->em = $em;
    }

    /**
     * {@inheritdoc}
     *
     * Check, if object supported by our converter
     */
    public function supports(ParamConverter $configuration)
    {
        if (!$configuration->getClass())
        {
            return false;
        }
        
        $reflection = new \ReflectionClass($configuration->getClass());
        if (!array_key_exists(HasTranslatable::class,$reflection->getInterfaces())){
            return false;
        }

        return true;
    }

    /**
     * {@inheritdoc}
     *
     * Applies converting
     *
     * @throws \InvalidArgumentException When route attributes are missing
     * @throws NotFoundHttpException     When object not found
     */
    public function apply(Request $request, ParamConverter $configuration)
    {
        $slug = $request->attributes->get('slug');

        // Check, if route attributes exists
        if (null === $slug) {
            throw new \InvalidArgumentException('Route attribute is missing');
        }
        $class = $configuration->getClass().'$';
        $translationClass = str_replace(ucfirst($configuration->getName().'$'), '', $class).'Translation'.'\\'.ucfirst($configuration->getName().'Translation');
        $categoryTrans    = $this->em->getRepository($translationClass)->findOneBy(['slug' => $slug]);
        if (!$categoryTrans)
        {
            throw new NotFoundHttpException();
        }
        $category         = $this->em->getRepository($configuration->getClass())->findOneBy(['id' => $categoryTrans->getTranslatable()->getId()]);

        $request->attributes->set($configuration->getName(), $category);

    }
}
