<?php

namespace App\DataFixtures;

use App\Entity\Event;
use App\Entity\EventMedia;
use App\Entity\EventStatus;
use App\Entity\Sponsor;
use App\Entity\EventDate;
use App\Entity\TypeEvent;
use App\Entity\EventSponsor;
use Psr\Log\LoggerInterface;
use App\Entity\EventPerformer;
use App\Utils\ImageFixturesHelper;
use Doctrine\Persistence\ObjectManager;
use Doctrine\Bundle\FixturesBundle\Fixture;
use Doctrine\Common\DataFixtures\DependentFixtureInterface;
use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;

class EventFixtures extends Fixture implements DependentFixtureInterface
{
    public function __construct(
        private LoggerInterface $logger, 
        private ParameterBagInterface $params
    ) {
        ini_set('memory_limit','256M');
    }

    private $youtube = [
        "https://www.youtube.com/watch?v=9_OCD1dNtOg",
        "https://www.youtube.com/watch?v=2Ul5uyq_3VY",
        "https://www.youtube.com/watch?v=doi1wJ0dfUE",
        "https://www.youtube.com/watch?v=YsvXTHfAMFY",
        "https://www.youtube.com/watch?v=sYRp8oP0yiw",
        "https://www.youtube.com/watch?v=eWupm_cePX8",
        "https://www.youtube.com/watch?v=9dLH5gO2DWs"
    ];
    private int $current_youtube = 0;
    private function __next_youtube_link () : string {
        $link = $this->youtube[$this->current_youtube];
        $this->current_youtube = ($this->current_youtube + 1) % count($this->youtube);
        return $link;
    }

    private int $current_image = 0;
    private int $NB_AVAILABLE_MEDIAS = 20;
    private function __next_image () : string {
        $link = "media_" . str_pad("".$this->current_image, 2, '0', STR_PAD_LEFT) . ".jpg";
        $this->current_image = ($this->current_image + 1) % $this->NB_AVAILABLE_MEDIAS;
        return $link;
    }

public function load(ObjectManager $manager): void
    {
        $fixtures_type = $this->params->get('app.fixtures-type');

        $imgHelper = new ImageFixturesHelper($this->logger);

        $raw_events = [

            [ 
                "title" => "Multicolored Ellington",
                "type" => "Spectacle",
                "image" => "jafo-laurent-mignard-duke-orchestra.jpg",
                "subject" => "Concert de Jazz",
                "sponsors" => [
                    ["sponsor" => "Festival Jazz au fil de l’Oise", "url" => "https://jazzaufildeloise.fr/laurent-mignard-duke-orchestra-multicolored-ellington-invite-nicolle-rochelle-khalid-k"],
                    ["sponsor" => "Points communs", "url" => "https://points-communs.fr"]
                ],
                "main_sponsor" => "Festival Jazz au fil de l’Oise",
                "dates" => [
                    [
                        "date" => "2023-12-01 20:00",
                        "place" => "Nouvelle scène nationale de Cergy-Pontoise / Val d’Oise",
                        "city" => "Pontoise"
                    ]
                ],
                "performers" => [
                    [ "name" => "Laurent Mignard Duke Orchestra" ],
                    [ "name" => "Nicolle Rochell" ],
                    [ "name" => "Khalid K." ],
                ]
            ],

            [ 
                "title" => "Univers sonores",
                "type" => "Atelier",
                "image" => "jafo-khalid-k-univers-sonore.jpg",
                "subject" => "Atelier de Jazz",
                "sponsors" => [
                    ["sponsor" => "Festival Jazz au fil de l’Oise", "url" => "https://jazzaufildeloise.fr/1-khalid-k-2-airs-2-cours-ndash-creation"],
                    ["sponsor" => "Points communs", "url" => "https://points-communs.fr"]
                ],
                "main_sponsor" => "Festival Jazz au fil de l’Oise",
                "dates" => [
                    [
                        "date" => "2023-11-22 14:00",
                        "place" => "École de musique",
                        "city" => "Vauréal"
                    ],
                    [
                        "date" => "2023-11-24 18:00",
                        "place" => "École de musique",
                        "city" => "Vauréal"
                    ],
                    [
                        "date" => "2023-11-29 11:00",
                        "place" => "École Quartier des Louvrais",
                        "city" => "Pontoise"
                    ]
                ],
                "performers" => [
                    [ "name" => "Khalid K." ],
                ]
            ]
        ];

        if ($fixtures_type == "test") {

            $raw_events[] = [ 
                    "title" => "Envol",
                    "type" => "Spectacle",
                    // "image" => "envoldr-1720x.jpg",
                    "video" => "LMzBmhtTFlQ",
                    "subject" => "Projet Trempoline",
                    "sponsors" => [
                        ["sponsor" => "Points communs", "url" => "https://points-communs.com/saison-2324/envol"],
                        ["sponsor" => "Festival des arts de la rue Cergy, Soit !", "url" => "https://www.cergysoit.fr/accueil/"],
                        ["sponsor" => "Le Moulin Fondu, Oposito", "url" => "http://www.oposito.fr/-PRIMO-5e-edition-du-9-septembre-au-446-.html"]
                    ],
                    "main_sponsor" => "Le Moulin Fondu, Oposito",
                    "dates" => [
                        [
                            "date" => "2023-09-15 17:00",
                            "place" => "Quartier des Louvrais",
                            "city" => "Pontoise"
                        ],
                    ],
                    "performers" => [
                        [ "name" => "Compagnie Hors Surface" ],
                    ]
                ];

            $raw_events[] = [ 
                    "title" => "Atelier trempoline",
                    "type" => "Atelier",
                    "image" => "envoldr-1720x_2.jpg",
                    "subject" => "Projet Trempoline",
                    "sponsors" => [
                        ["sponsor" => "Points communs", "url" => "https://points-communs.com/saison-2324/envol"],
                        ["sponsor" => "Festival des arts de la rue Cergy, Soit !", "url" => "https://www.cergysoit.fr/accueil/"],
                        ["sponsor" => "Le Moulin Fondu, Oposito", "url" => "http://www.oposito.fr/-PRIMO-5e-edition-du-9-septembre-au-446-.html"]
                    ],
                    "main_sponsor" => "Le Moulin Fondu, Oposito",
                    "dates" => [
                        [
                            "date" => "2023-09-14 14:00",
                            "place" => "Quartier des Louvrais",
                            "city" => "Pontoise"
                        ],
                        [
                            "date" => "2023-09-15 14:00",
                            "place" => "Quartier des Louvrais",
                            "city" => "Pontoise"
                        ],
                        [
                            "date" => "2023-09-16 14:00",
                            "place" => "Quartier des Louvrais",
                            "city" => "Pontoise"
                        ],
                    ],
                    "performers" => [
                        [ "name" => "Compagnie Hors Surface" ],
                    ]
                ];

            $raw_events[] = [ 
                    "title" => "Variability",
                    "type" => "Spectacle-rencontre",
                    // "image" => "0702-Variability-Cie-Ex-novo-Frederic-Iovino-1-web2000.jpg",
                    "video" => "9_OCD1dNtOg",
                    "subject" => "Cap sur la Danse",
                    "sponsors" => [
                        ["sponsor" => "Fondation Royaumont", "url" => "https://www.royaumont.com/evenement/spectacle-rencontre-variability/?date=02/07/2023T15:30"]
                    ],
                    "main_sponsor" => "Fondation Royaumont",
                    "dates" => [
                        [
                            "date" => "2023-07-02 15:30",
                            "place" => "Abbaye",
                            "city" => "Royaumont"
                        ]
                    ],
                    "performers" => [
                        [ "name" => "Eve Bouchelot" ],
                        [ "name" => "Constance Diard" ],
                        [ "name" => "Lucie Gemon" ],
                    ]
                ];

            $raw_events[] = [ 
                    "title" => "Cycle [lumières sur la création]",
                    "type" => "Spectacle-rencontre",
                    "image" => "concert-academie-voix-nouvelles-Royaumont-2021-FM-11_.jpg",
                    "subject" => "Jeunes talents de la musique d’aujourd’hui",
                    "sponsors" => [
                        ["sponsor" => "Fondation Royaumont", "url" => "https://www.royaumont.com/evenement/concert-rencontre-jeunes-talents-de-la-musique-daujourdhui/?date=09/07/2023T15:30"]
                    ],
                    "main_sponsor" => "Fondation Royaumont",
                    "dates" => [
                        [
                            "date" => "2023-07-09 15:30",
                            "place" => "Grand comble",
                            "city" => "Royaumont"
                        ]
                    ],
                    "performers" => [
                        [ "name" => "Ensemble Ulysses" ],
                    ]
                ];

            $raw_events[] = [ 
                    "title" => "Radio 2000 – Opus 2",
                    "type" => "Spectacle",
                    "image" => "ciedugrandhotelradio2000opus2creditgh-scaled.jpg",
                    "subject" => "Caravane • Magie • Théâtre d'objets",
                    "sponsors" => [
                        ["sponsor" => "Pôle itinérant en Val d’Oise", "url" => "https://www.le-pivo.fr/evenements/radio-2000-cie-grand-hotel/"],
                        ["sponsor" => "Points communs", "url" => "https://points-communs.fr"]
                    ],
                    "main_sponsor" => "Pôle itinérant en Val d’Oise",
                    "dates" => [
                        [
                            "date" => "2023-06-30 17:00",
                            "place" => "Place de l'Eglise",
                            "city" => "Epiais-Rhus"
                        ],
                        [ "date" => "2023-07-01 11:00", "place" => "Plateau sportif", "city" => "Cléry-en-Vexin" ],
                        [ "date" => "2023-07-01 12:00", "place" => "Plateau sportif", "city" => "Cléry-en-Vexin" ],
                        [ "date" => "2023-07-01 15:00", "place" => "Plateau sportif", "city" => "Cléry-en-Vexin" ],
                        [ "date" => "2023-07-01 16:00", "place" => "Plateau sportif", "city" => "Cléry-en-Vexin" ],
                        [ "date" => "2023-07-02 10:00", "place" => "Place Saint-Martin", "city" => "Omerville" ],
                        [ "date" => "2023-07-02 11:00", "place" => "Place Saint-Martin", "city" => "Omerville" ],
                        [ "date" => "2023-07-02 12:00", "place" => "Place Saint-Martin", "city" => "Omerville" ],
                        [ "date" => "2023-07-02 16:00", "place" => "Place Saint-Martin", "city" => "Omerville" ],
                    ],
                    "performers" => [
                        [ "name" => "Compagnie du Grand Hôtel" ],
                    ]
                ];

            $raw_events[] = [ 
                    "title" => "Josette et Mustapha",
                    "type" => "Spectacle",
                    "image" => "josette-et-mustapha-lacoursinguliere-scaled.jpg",
                    "subject" => "Marionnette",
                    "sponsors" => [
                        ["sponsor" => "Pôle itinérant en Val d’Oise", "url" => "https://www.le-pivo.fr/evenements/josette-et-mustapha-cie-la-cour-singuliere/"]
                    ],
                    "main_sponsor" => "Pôle itinérant en Val d’Oise",
                    "dates" => [
                        [
                            "date" => "2023-06-25 17:00",
                            "place" => "Espace vert, parking de la Mairie",
                            "city" => "Magny-en-Vexin"
                        ],
                    ],
                    "performers" => [
                        [ "name" => "Compagnie La cour singulière" ],
                    ]
                    ];
        };

        $i_rep_max = ($fixtures_type == 'test' ? 5 : 1);
        $now = new \DateTime("now");

        for ($i_rep=0; $i_rep < $i_rep_max; $i_rep++) { 
            foreach ($raw_events as $r_event) {

                $typeevent = $manager->getRepository(TypeEvent::class)->findOneBy(["name" => $r_event["type"]]);

                if (!$typeevent) { throw new \Exception("Type event non trouvé : ".$r_event["type"]); }

                $title = $r_event["title"];
                if ($i_rep > 0) {
                    $title = $title . ' ' . ($i_rep+1);
                }

                $event = new Event();
                $event->setTitle($title)
                    // ->setImgPresentationFile($image)
                    ->setSubject($r_event["subject"])
                    ->setType($typeevent)
                    ->setActive(true);

                // dump($r_event);

                if (array_key_exists("image", $r_event)) {
                    $image = $imgHelper->prepareUploadedFile($r_event["image"], "events");
                    $event->setImgPresentationFile($image);
                }

                if (array_key_exists("video", $r_event)) {
                    $event->setVideoPresentation("https://www.youtube.com/watch?v=" . $r_event["video"]);
                }

                foreach ($r_event["sponsors"] as $r_sponsor) {
                    $sponsor = $manager->getRepository(Sponsor::class)->findOneBy(["name" => $r_sponsor["sponsor"]]);
                    if (!$sponsor) { throw new \Exception("Sponsor non trouvé : ".$r_sponsor["sponsor"]); }

                    $event_sponsor = new EventSponsor();
                    $event_sponsor->setEvent($event)
                        ->setSponsor($sponsor)
                        ->setUrl($r_sponsor["url"])
                        ->setMain($r_sponsor["sponsor"] == $r_event["main_sponsor"]);

                    $manager->persist($event_sponsor);
                    
                    $event->addSponsor($event_sponsor);
                }

                $status = "pending";
                foreach ($r_event["dates"] as $r_date) {
                    $event_date = new EventDate();
                    $date = new \DateTime($r_date["date"]);

                    if ($i_rep > 0) {
                        date_add($date, new \DateInterval("P21D"));
                    }

                    if ($date < $now) {
                        $status = 'done';
                    }

                    $event_date->setEvent($event)
                        ->setDate($date)
                        ->setPlace($r_date["place"])
                        ->setCity($r_date["city"]);

                    $manager->persist($event_date);
                    
                    $event->addDate($event_date);
                }

                foreach ($r_event["performers"] as $r_performer) {
                    $event_performer = new EventPerformer();
                    $event_performer->setEvent($event)
                        ->setName($r_performer["name"]);
                        // ->setOrdre(++$i_perf);
                    $manager->persist($event_performer);
                    
                    $event->addPerformer($event_performer);
                }

                if ($status == "done") {
                    $nb_medias = random_int(0, 5);

                    for ($i_media=0; $i_media < $nb_medias; $i_media++) { 
                        $is_video = (random_int(0, 7) == 3);

                        $event_media = new EventMedia();
                        $event_media->setEvent($event);

                        if ($is_video) {
                            $event_media->setVideoMedia($this->__next_youtube_link());
                        } else {
                            $image = $imgHelper->prepareUploadedFile($this->__next_image(), "medias");
                            $event_media->setImgMediaFile($image);
                        }

                        $manager->persist($event_media);
                    }
                }
                $manager->persist($event);

            }
        }

        $manager->flush();
    }

    public function getDependencies()
    {
        return [
            SponsorFixtures::class,
            TypeEventFixtures::class,
        ];
    }
}
