<?php

namespace Comitium5\DesignerBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;

/**
 * Class LinksController
 *
 * @author Óscar Jiménez <oscarjg19.developer@gmail.com>
 * @package ComitiumSuite\Bundle\CoreBundle\Controller
 */
class LinksController extends Controller
{
    /**
     * @param Request $request
     * @return JsonResponse
     * @throws \Exception
     */
    public function generateAction(Request $request)
    {
        $entityId     = $request->query->get('id');
        $entityClass  = $request->query->get('className');
        $locale       = $request->query->get('locale');

        if ($locale === null) {
            $locale = $this->get("cs.provider.locale")->getDefaultLocale()->getCode();
        }

        $entity = $this
            ->get('doctrine.orm.default_entity_manager')
            ->getRepository($entityClass)
            ->find($entityId);

        if (!$entity) {
            throw new \Exception('Entity was not found');
        }

        if ($entity instanceof SubsiteRelationInterface) {
            $subSite = $entity->getSubsite();
        } elseif ($entity instanceof SubsiteCollectionInterface) {
            $subSite = $entity->getSubsites()->first();
        } else {
            $subSite = $this
                ->get("cs.provider.subsite")
                ->getSubSite();
        }

        $routingProvider = $this->get("cs.provider.routing");

        $links = $routingProvider
            ->setSubSite($subSite)
            ->setRouterBySubSite($subSite)
            ->generateAll($entity)
        ;

        $link = isset($links[$locale]) ? $links[$locale] : null;

        return new JsonResponse([
            'link'  => $link,
            'links' => $links,
        ]);
    }

    /**
     * @param Request $request
     * @return \Symfony\Component\HttpFoundation\Response
     */
    public function renderAction(Request $request)
    {
        return $this->render('Comitium5DesignerBundle:Links:modal.html.twig', [
            'link' => $request->query->get('link', null)
        ]);
    }
}
