<?php

/*
 * kohinos_cooperatic
 * Copyright (C) 2019-2020  ADML63
 * Copyright (C) 2020- Cooperatic
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published
 * by the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
 
namespace App\Controller;

use App\Entity\Prestataire;
use App\Entity\Comptoir;
use App\Entity\Groupeprestataire;
use Doctrine\ORM\EntityManagerInterface;
use Sonata\MediaBundle\Provider\Pool;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Routing\RouterInterface;
use Sonata\MediaBundle\Twig\Extension\MediaExtension;
use Symfony\Component\HttpFoundation\Request;

class MapController extends AbstractController
{
    public function __construct(EntityManagerInterface $em, RouterInterface $router, Pool $mediaext)
    {
        $this->em = $em;
        $this->router = $router;
        $this->mediaext = $mediaext;
    }

    /**
     * @Route(
     *     name="papi_poi_all",
     *     path="/public/poi/all",
     *     methods={"GET"},
     *     defaults={
     *         "_api_resource_class"=Map::class,
     *         "_api_item_operation_name"="get_all_poi"
     *     }
     * )
     */
    public function __invoke(Request $request)
    {
        // @TODO : à tester plus !
        if ($request->query->has('geoloc') && $request->query->has('distance')) {
            $geoloc = json_decode($request->query->get('geoloc'));
            $lat = $geoloc[0];
            $lon = $geoloc[1];
            $distance = intval($request->query->get('distance'));
            $prestas = $this->em->getRepository(Prestataire::class)->findByGeoloc($lat, $lon, $distance);
            $comptoirs = $this->em->getRepository(Comptoir::class)->findByGeoloc($lat, $lon, $distance);
            $groupeprestataires = $this->em->getRepository(Groupeprestataire::class)->findByGeoloc($lat, $lon, $distance);
        } else {
            $prestas = $this->em->getRepository(Prestataire::class)->findBy(array('enabled' => true, 'mlc' => false), array('raison'=> 'ASC'));
            $comptoirs = $this->em->getRepository(Comptoir::class)->findBy(array('enabled' => true), array('name'=> 'ASC'));
            $groupeprestataires = $this->em->getRepository(Groupeprestataire::class)->findBy(array('enabled' => true), array('name'=> 'ASC'));
        }

        $data = [];
        $count = 0;
        foreach ($prestas as $presta) {
            if (count($presta->getGeolocs()) > 0) {
                foreach ($presta->getGeolocs() as $geolocp) {
                    if ($geolocp->isEnabled() && $geolocp->getGeoloc()->getLat() != null && $geolocp->getGeoloc()->getLon() != null) {
                        $data[$count]['name'] = $presta->__toString();
                        $data[$count]['content'] = $presta->getDescription();
                        $data[$count]['web'] = $presta->getWeb();
                        $data[$count]['link'] = $this->router->generate('show_prestataire', ['slug' => $presta->getSlug()]);
                        $data[$count]['hours'] = $presta->getHoraires();
                        if ($presta->getMedia() != null) {
                            $data[$count]['thumbnail'] = $this->path($presta->getMedia(), 'small', $request);
                        }
                        $data[$count]['geolocs'][] = $geolocp;
                        if (count($presta->getRubriques()) > 0) {
                            foreach ($presta->getRubriques() as $rub) {
                                $data[$count]['rubriques'][] = [
                                    'name' => $rub->getName(),
                                    'url' => $this->router->generate('show_rubrique', ['slug' => $rub->getSlug()]),
                                ];
                            }
                            if ($presta->getRubriques()[0]->getMedia() != null) {
                                $data[$count]['icon'] = $this->path($presta->getRubriques()[0]->getMedia(), 'preview', $request);
                            }
                        }
                        $count++;
                    }
                }
            }
        }

        foreach ($comptoirs as $comptoir) {
            if ($comptoir->getGeoloc() != null && $comptoir->getGeoloc()->getLat() != null && $comptoir->getGeoloc()->getLon() != null) {
                $data[$count]['name'] = $comptoir->__toString();
                $data[$count]['content'] = $comptoir->getContent();
                $data[$count]['geolocs'][] = $comptoir->getGeoloc();
                $data[$count]['link'] = $this->router->generate('show_comptoir', ['slug' => $comptoir->getSlug()]);
                if ($comptoir->getMedia() != null) {
                    $data[$count]['thumbnail'] = $this->path($comptoir->getMedia(), 'small', $request);
                }
                $count++;
            }
        }

        foreach ($groupeprestataires as $groupeprestataire) {
            if ($groupeprestataire->getGeoloc() != null && $groupeprestataire->getGeoloc()->getLat() != null && $groupeprestataire->getGeoloc()->getLon() != null) {
                $data[$count]['name'] = $groupeprestataire->__toString();
                $data[$count]['content'] = $groupeprestataire->getContent();
                $data[$count]['geolocs'][] = $groupeprestataire->getGeoloc();
                $data[$count]['hours'] = $groupeprestataire->getHoraires();
                $data[$count]['link'] = $this->router->generate('show_groupeprestataire', ['slug' => $groupeprestataire->getSlug()]);
                // if ($groupeprestataire->getMedia() != null) {
                //     $data[$count]['thumbnail'] = $this->path($groupeprestataire->getMedia(), 'small', $request);
                // }
                foreach ($groupeprestataire->getPrestataires() as $presta) {
                    $groupeprestaData = [
                        'name' => $presta->__toString(),
                        'link' => $this->router->generate('show_prestataire', ['slug' => $presta->getSlug()])
                    ];
                    if (count($presta->getRubriques()) > 0) {
                        if ($presta->getRubriques()[0]->getMedia() != null) {
                            $groupeprestaData['rubrique']['name'] = $presta->getRubriques()[0]->getName();
                            $groupeprestaData['rubrique']['icon'] = $this->path($presta->getRubriques()[0]->getMedia(), 'preview', $request);
                        }
                    }
                    $data[$count]['prestataires'][] = $groupeprestaData;
                }
                $count++;
            }
        }

        return $data;
    }

    private function path($media, $format, $request)
    {
        if (!$media) {
            return '';
        }

        $provider = $this->mediaext
           ->getProvider($media->getProviderName());

        $format = $provider->getFormatName($media, $format);

        return $request->getSchemeAndHttpHost().$provider->generatePublicUrl($media, $format);
    }
}
