<?php

namespace Ayaline\Bundle\EzAgendaCollectivitesBundle\Twig;

use Twig_Extension;
use Twig_SimpleFilter;
use Twig_SimpleFunction;
use eZ\Publish\API\Repository\Repository;
use Symfony\Component\DependencyInjection\ContainerInterface;

class ToolsExtension extends \Twig_Extension
{

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

    /**
     * @var ContainerInterface
     */
    private $container;

    public function __construct(Repository $repository,ContainerInterface $container)
    {
        $this->container = $container;
        $this->repository = $repository;
    }

    public function getFunctions()
    {

        return array(
            new \Twig_SimpleFunction(
                'get_coordonnees_event',
                array($this, 'getCoordonneesEvent'),
                array('is_safe' => array('html'))
            )
        );
    }


    public function getCoordonneesEvent($contentId, $withName = true){

        $lieuxIds = array();
        $lieuName = '';
        $contentService = $this->repository->getContentService();
        $locationService = $this->repository->getLocationService();
        $content = $contentService->loadContent($contentId);
        $LieuCoordonnes = $content;

        if ($content->getFieldValue('localiser_lieu')->destinationContentId !== null && !in_array($content->getFieldValue('localiser_lieu')->destinationContentId, $lieuxIds)) {
            $contentLieu = $contentService->loadContent($content->getFieldValue('localiser_lieu')->destinationContentId);
            $locationLieu = $contentLieu->contentInfo->mainLocationId != null ? $locationService->loadLocation($contentLieu->contentInfo->mainLocationId) : null;

            if($locationLieu !==null && !$locationLieu->hidden && $contentLieu->contentInfo->mainLocationId != $content->contentInfo->mainLocationId){
                if($withName){
                    $lieuName = trim($contentLieu->getFieldValue('titre')->text);
                }
                array_push($lieuxIds, $contentLieu->contentInfo->id);
                $coordonnes = $this->getCoordonneesEvent($contentLieu->contentInfo->id, false);
                $LieuCoordonnes = $coordonnes['LieuCoordonnes'];
            }
        }

        return array(
            'lieuName' => $lieuName,
            'LieuCoordonnes' => $LieuCoordonnes
        );
    }

    public function getName()
    {
        return 'agenda_extension';
    }
}

?>