<?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){

        $lieuxIds = array();
        $Lieucoordonnes = array();
        $helperContent = $this->container->get('ayaline_tools.tools.content');
        $contentService = $this->repository->getContentService();

        $content = $contentService->loadContent($contentId);


        if($content->getFieldValue('adresse')->text != '' or $content->getFieldValue('code_postal')->text != '' or $content->getFieldValue('commune')->text != '' or ($content->getFieldValue('geolocalisation')->latitude !== null && $content->getFieldValue('geolocalisation')->longitude !== null )){
            $Lieucoordonnes =$content;
        }
        elseif ($content->getFieldValue('localiser_lieu')->destinationContentId !== null && !in_array($content->getFieldValue('localiser_lieu')->destinationContentId, $lieuxIds)) {

            $contentLieu = $contentService->loadContent($content->getFieldValue('localiser_lieu')->destinationContentId);
            array_push($lieuxIds, $contentLieu->contentInfo->id);

            $Lieucoordonnes = $this->getCoordonneesEvent($contentLieu->contentInfo->id);
        }

        return $Lieucoordonnes;
    }

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

?>