<?php

namespace App\Controller;

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

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)->findDefault();
            $comptoirs = $this->em->getRepository(Comptoir::class)->findBy(['enabled' => true], ['name' => 'ASC']);
            $groupeprestataires = $this->em->getRepository(Groupeprestataire::class)->findBy(['enabled' => true], ['name' => 'ASC']);
        }

        $data = [];
        $count = 0;
        foreach ($prestas as $presta) {
            if (count($presta->getGeolocs()) > 0) {
                foreach ($presta->getGeolocs() as $geolocp) {
                    if ($geolocp->isEnabled() && null != $geolocp->getGeoloc()->getLat() && null != $geolocp->getGeoloc()->getLon()) {
                        $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 (null != $presta->getMedia()) {
                            $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 (null != $presta->getRubriques()[0]->getMedia()) {
                                $data[$count]['icon'] = $this->path($presta->getRubriques()[0]->getMedia(), 'preview', $request);
                            }
                        }
                        ++$count;
                    }
                }
            }
        }

        foreach ($comptoirs as $comptoir) {
            if (null != $comptoir->getGeoloc() && null != $comptoir->getGeoloc()->getLat() && null != $comptoir->getGeoloc()->getLon()) {
                $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 (null != $comptoir->getMedia()) {
                    $data[$count]['thumbnail'] = $this->path($comptoir->getMedia(), 'small', $request);
                }
                ++$count;
            }
        }

        foreach ($groupeprestataires as $groupeprestataire) {
            if (null != $groupeprestataire->getGeoloc() && null != $groupeprestataire->getGeoloc()->getLat() && null != $groupeprestataire->getGeoloc()->getLon()) {
                $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 (null != $presta->getRubriques()[0]->getMedia()) {
                            $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);
    }
}
