<?php

namespace Ayaline\Bundle\EzDiaporamaBundle\Controller;

use eZ\Bundle\EzPublishCoreBundle\Controller;
use eZ\Publish\API\Repository\Exceptions\NotFoundException;
use eZ\Publish\API\Repository\Values\Content\Query;
use eZ\Publish\API\Repository\Values\Content\Query\Criterion;
use eZ\Publish\API\Repository\Values\Content\Query\SortClause;

class SlideShowController extends Controller
{
    /**
     * @param \Symfony\Component\DependencyInjection\ContainerInterface $container
     * @param \eZ\Publish\API\Repository\Repository $repository
     * @param \Symfony\Component\HttpKernel\LoggerInterface $logger
     */
    /*
    public function __construct( ContainerInterface $container, Repository $repository, LoggerInterface $logger )
    {
        $this->container = $container;
        $this->repository = $repository;
        $this->logger = $logger;
    }
     */

    /**
     * Get the slideshow of the given location
     * @param int $rootLocationId
     * @return string template as html
     */
    public function slideShowAction($rootLocationId = 0)
    {
        $repository = $this->getRepository();
        $contentService = $repository->getContentService();
        $locationService = $repository->getLocationService();
        $toolsContent = $this->get('ayaline_tools.tools.content');
        $slides = array();
        $rootLocation = $this->getRootLocation();
        $locationIdRoot = $rootLocation->id;
        $isHomePage = false;
        $contentsForTemplates = array();
        try {
            if ($rootLocationId == 0 ) {
                $rootLocationId = $rootLocation->id;
            }
            if ($rootLocationId == $locationIdRoot) {
                $isHomePage = true;
            }
            //get the slideshow
            $slideshow = $this->getSlideShowOfLocationId($rootLocationId);

            if ($slideshow) {
                $slides = $toolsContent->contentList(
                    $slideshow->contentInfo->mainLocationId,
                    array('diapo'),
                    array(new SortClause\LocationPriority())
                );
            }

            //get texts and links

        foreach ($slides as $slide) {
            $diapoLinksContents = $toolsContent->contentList(
                $slide->contentInfo->mainLocationId,
                array('accroche_diapo')
            );
            $slideContentId = $slide->contentInfo->id;

            //get all links
                foreach ($diapoLinksContents as $diapoLinksContent) {
                    //create a specific array for the templates
                    $diapoLinksForTemplates = array();
                    $diapoLinksForTemplates['content'] = $diapoLinksContent;
                    $diapoLinksForTemplates['subtitle'] = (string)$diapoLinksContent->getField('subtitle')->value;
                    $diapoLinksForTemplates['external_link'] = false;
                    $diapoLinksForTemplates['internal_location'] = false;
                    $diapoLinksForTemplates['new_window'] = $diapoLinksContent->getField('new_window')->value;
                    $coordinates = explode(',', $diapoLinksContent->getField('coordinates')->value);
                    if (count($coordinates) == 2) {
                        $diapoLinksForTemplates['offset-left'] = $coordinates[0];
                        $diapoLinksForTemplates['offset-top'] = $coordinates[1];
                    } else {
                        $diapoLinksForTemplates['offset-left'] = false;
                        $diapoLinksForTemplates['offset-top'] = false;
                    }


                    //manage the internal or external link
                    $destinationContentId = $diapoLinksContent->getFieldValue(
                        'internal_link'
                    )->destinationContentId;
                    if ($destinationContentId) {
                        $destinationContent = $contentService->loadContent($destinationContentId);
                        $destinationLocation = $locationService->loadLocation(
                            $destinationContent->contentInfo->mainLocationId
                        );
                        $diapoLinksForTemplates['internal_location'] = $destinationLocation;
                    } else {
                        if ($diapoLinksContent->getField('external_link')->value) {
                            $diapoLinksForTemplates['external_link'] = $diapoLinksContent->getField(
                                'external_link'
                            )->value->link;
                        } else {
                            $diapoLinksForTemplates['external_link'] = null;
                        }
                    }

                    //index information by slide contentId
                    $contentsForTemplates[$slideContentId][] = $diapoLinksForTemplates;
                }
            }
        } catch (\eZ\Publish\Core\Base\Exceptions\UnauthorizedException $e) {
            $logger = $this->get('logger');
            $logger->err("Diaporama : un contenu de diaporama n'est pas autorisé : " . $e->getMessage());
        }
        $response = $this->render(
            'AyalineEzDiaporamaBundle:Default:slideshow.html.twig',
            array(
                'slides' => $slides,
                'contentsForTemplates' => $contentsForTemplates,
                'isHomePage' => $isHomePage,
            )
        );
        $response->headers->set('X-Location-Id', $locationIdRoot);
        // 1 jour
        $response->setSharedMaxAge(86400);
        return $response;
    }

    /**
     * Get a slideshow location id associated to a lcoation id. Return false if none is found.
     * @param int $locationId
     * @return false | Slideshow Content
     */
    protected function getSlideShowLocationId($locationId)
    {

        $repository = $this->getRepository();
        $contentService = $repository->getContentService();
        $locationService = $repository->getLocationService();
        $contentTypeService = $repository->getContentTypeService();
        $toolsContent = $this->get('ayaline_tools.tools.content');

        //get the reverse relation of the location
        $location = $locationService->loadLocation($locationId);
        $reverseRelations = $contentService->loadReverseRelations($location->getContentInfo());
        //loop on these relations, and get the first one of type "diaporama"
        foreach ($reverseRelations as $reverseRelation) {

            //get the source location
            $sourceContentInfo = $reverseRelation->getSourceContentInfo();

            //get the content type of the source
            $contentType = $contentTypeService->loadContentType($sourceContentInfo->contentTypeId);

            //keep it if it matches
            if ($contentType->identifier == 'diaporama') {
                $slideShowContent = $toolsContent->getContentWithVisibility($sourceContentInfo->id);

                if ($slideShowContent) {
                    //we have a content !
                    return $slideShowContent;
                    //return $slideShowContent->contentInfo->mainLocationId;
                }
            }
        }

        return false;
    }

    /**
     * Determine which slideshow is associated to a location id
     * @param integer $location
     * @return Content Slideshow | false
     */
    protected function getSlideShowOfLocationId($locationId)
    {

        $repository = $this->getRepository();
        $locationService = $repository->getLocationService();
        $toolsContent = $this->get('ayaline_tools.tools.content');
        $currentSiteaccessName = $this->getRequest()->get('siteaccess')->name;
        $locationIdMediatheque = $this->container->hasParameter('location_id.mediatheque.' . $currentSiteaccessName) ?
            $this->container->getParameter('location_id.mediatheque.' . $currentSiteaccessName) :
            $this->container->getParameter('location_id.mediatheque');
        $slideshowList = $toolsContent->contentTree(
            $locationIdMediatheque,
            array('diaporama')
        );
        $slideshowContent = false;
        try {
            $location = $locationService->loadLocation($locationId);
        } catch (NotFoundException $exception) {
            foreach ($slideshowList as $slideshowContentElement) {
                if ($slideshowContentElement->getField('default')->value->bool == true) {
                    return $slideshowContentElement;
                }
            }
        }

        $pathString = $location->pathString;
        $pathLocations = explode('/', $pathString);
        //4 = root
        if (count($pathLocations) > 2) {
            $slideshowContent = $this->getSlideShowLocationId($pathLocations[count($pathLocations) - 2]);

            if ($slideshowContent) {
                return $slideshowContent;
            }
        }

        // pathstring example : /1/2/97/4
        // => pathLocations : Array ( [0] => [1] => 1 [2] => 2 [3] => 97 [4] => )
        // location #2 is special case so we mustn't use it
        // stop as soon as we have a slideshow

        for ($i = count($pathLocations) - 2; $i >= 3; $i--) {
            $slideshowContent = $this->getSlideShowLocationId($pathLocations[$i]);
            if ($slideshowContent) {
                break;
            }
        }

        if ($slideshowContent) {
            //check if we have to
            $applyToSubtree = $slideshowContent->getField('subtree')->value->bool;
            if ($applyToSubtree) {
                return $slideshowContent;
            }
        }
        foreach ($slideshowList as $slideshowContent) {
            if ($slideshowContent->getField('default')->value->bool == true) {
                return $slideshowContent;
            }
        }

        return false;
    }

    /**
     * @var \Symfony\Component\DependencyInjection\ContainerInterface
     */
    protected $container;

    /**
     * @var \eZ\Publish\API\Repository\Repository
     */
    protected $repository;

    /**
     * @var \Symfony\Component\HttpKernel\Log\LoggerInterface
     */
    protected $logger;
}
