from ..twosteps_extractor import *
import json5
from bs4 import BeautifulSoup

# A class dedicated to get events from La Coopérative de Mai:
# URL: https://lacomediedeclermont.com/saison23-24/wp-admin/admin-ajax.php?action=load_dates_existantes
# URL pour les humains: https://lacomediedeclermont.com/saison24-25/
class CExtractor(TwoStepsExtractor):
    nom_lieu = "La Comédie de Clermont"
    url_referer = "https://lacomediedeclermont.com/saison24-25/"

    def is_to_import_from_url(self, url):
        if any(keyword in url for keyword in ["podcast", "on-debriefe", "popcorn", "rencontreautour","rencontre-autour","les-cles-du-spectacle"]):
            return False
        else:
            return True

    def category_comedie2agenda(self, category):
        mapping = {
            "Théâtre": "Spectacles",
            "Danse": "Spectacles",
            "Rencontre": "Rencontres & Débats",
            "Sortie de résidence": "Sans catégorie",
            "PopCorn Live": "Sans catégorie",
        }
        mapping_tag = {
            "Théâtre": "🎭 théâtre",
            "Danse": "💃 danse",
            "Rencontre": None,
            "Sortie de résidence": "sortie de résidence",
            "PopCorn Live": None,
        }
        if category in mapping:
            return mapping[category], mapping_tag[category]
        else:
            return None, None

    def build_event_url_list(self, content):
        dates = json5.loads(content)["data"][0]

        url = self.url.split("?")[0]
        for d in list(set(dates)):
            if not self.only_future or self.now <= datetime.date.fromisoformat(d):
                events = self.downloader.get_content(
                    url,
                    post={"action": "load_evenements_jour", "jour": d},
                    referer="https://lacomediedeclermont.com/saison24-25/"
                )
                if events:
                    events = json5.loads(events)
                    if "data" in events:
                        events = events["data"][0]
                        soup = BeautifulSoup(events, "html.parser")
                        events = soup.select("div.unedatedev")
                        for e in events:
                            e_url = (
                                e.select("a")[0]["href"] + "#" + d
                            )  # a "fake" url specific for each day of this show

                            if self.is_to_import_from_url(e_url):
                                self.add_event_url(e_url)
                                self.add_event_start_day(e_url, d)
                                t = (
                                    str(e.select("div#datecal")[0])
                                    .split(" ")[-1]
                                    .split("<")[0]
                                )
                                self.add_event_start_time(e_url, t)
                                title = e.select("a")[0].contents[0]
                                self.add_event_title(e_url, title)
                                category = e.select("div#lieuevtcal span")
                                if len(category) > 0:
                                    category, tag = self.category_comedie2agenda(
                                        category[-1].contents[0]
                                    )
                                    if category:
                                        self.add_event_category(e_url, category)
                                    if tag:
                                        self.add_event_tag(e_url, tag)
                                location = (
                                    e.select("div#lieuevtcal")[0]
                                    .contents[-1]
                                    .split("•")[-1]
                                )
                                if location.replace(" ", "") == "":
                                    location = self.nom_lieu
                                self.add_event_location(e_url, location)

    def add_event_from_content(
        self,
        event_content,
        event_url,
        url_human=None,
        default_values=None,
        published=False,
    ):
        soup = BeautifulSoup(event_content, "html.parser")

        image = soup.select("#imgspec img")
        if image and len(image) > 0:
            image = image[0]["src"]
        else:
            image = None


        description = soup.select("#descspec")
        if description and len(description) > 0:
            description = description[0].get_text().replace("Lire plus...", "")
            # on ajoute éventuellement les informations complémentaires

            d_suite = ""
            for d in ["#typespec", "#dureespec", "#lieuspec", ".lkuncontdroitespec"]:
                comp_desc = soup.select(d)
                if comp_desc and len(comp_desc) > 0:
                    for desc in comp_desc:
                        d_suite += "\n\n" + desc.get_text()
            if d_suite != "":
                description += "\n\n> Informations complémentaires:" + d_suite
        else:
            description = None

        url_human = event_url

        self.add_event_with_props(
            default_values,
            event_url,
            None,
            None,
            None,
            None,
            description,
            [],
            recurrences=None,
            uuids=[event_url],
            url_human=url_human,
            published=published,
            image=image,
        )
