from datetime import date, datetime
from urllib.parse import urlparse
from chronostring import parse_dates
import re

from bs4 import BeautifulSoup

from ..twosteps_extractor import TwoStepsExtractorNoPause


# A class dedicated to get events from Mille formes
# URL: https://www.milleformes.fr/programme
class CExtractor(TwoStepsExtractorNoPause):
    def extract(
        self,
        content,
        url,
        url_human=None,
        default_values=None,
        published=False,
        only_future=True,
        ignore_404=True,
    ):
        self.root_address = "https://" + urlparse(url).netloc + "/"
        self.today = date.today()
        return super().extract(
            content,
            url,
            url_human,
            default_values,
            published,
            only_future,
            ignore_404,
        )

    def parse_category(self, cat):
        cat = cat.replace("\n", "").strip()
        if "exposition" in cat or "dispositif artistique interactif" in cat:
            result = "Visites & Expositions"
        elif "atelier" in cat:
            result = "Animations & Ateliers"
        elif cat in ["buffet"]:
            result = "Rendez-vous locaux"
        elif "ciné" in cat:
            result = "Cinéma"
        elif "concert" in cat:
            result = "Fêtes & Concerts"
        elif "rencontre" in cat:
            result = "Rencontres & Débats"
        elif "spectacle" in cat:
            result = "Spectacles"
        else:
            result = "Sans catégorie"

        return result

    def build_event_url_list(self, content, infuture_days=180):
        soup = BeautifulSoup(content, "html.parser")
        links = soup.select(".cell a.evenement")
        for lk in links:
            self.add_event_url(self.root_address + lk["href"])

    def add_event_from_content(
        self,
        event_content,
        event_url,
        url_human=None,
        default_values=None,
        published=False,
    ):
        soup = BeautifulSoup(event_content, "html.parser")
        title = soup.select_one("h1").text.replace("\n", "").strip().title()

        image = soup.select_one(".slide img")
        if image is None:
            image_alt = ""
        else:
            image_alt = image["alt"]
            image = self.root_address + image["src"]

        soustitre = soup.select_one(".sous-titre")
        if soustitre is not None:
            soustitre = soustitre.text.strip()

        description = soup.select_one(".texte-full").text.strip()
        infos = soup.select_one(".champ .infos")
        if infos is not None:
            infos = infos.text

        location = soup.select_one(".champ .taxo.espace").text.strip()

        soup.select_one(".champ.taxo-age").text
        category = self.parse_category(soup.select_one(".champ.categorie").text)

        dt = soup.select_one(".champ.date-libre").text

        description = "\n\n".join(
            [x for x in [soustitre, description, dt, infos] if x is not None]
        )

        if (
            " au " in dt
            or dt.startswith("Du")
            or dt.lower().strip() == "en continu"
            or dt.startswith("Les")
        ):
            return

        dates = []
        for dl in dt.split("\n"):
            if re.match(r".* ans[  ]*:.*", dt):
                dates += parse_dates(dt.split(":")[1])
            else:
                dates += parse_dates(dt)

        for d in dates:
            start_day = None
            start_time = None
            end_day = None
            end_time = None
            if isinstance(d, datetime):
                start_day = d.date()
                start_time = d.time()
            elif isinstance(d, date):
                start_day = d
            elif isinstance(d, list) and len(d) == 2:
                start_day = d[0].date()
                start_time = d[0].time()
                end_day = d[1].date()
                end_time = d[1].time()

            if start_day is not None:
                uuid = event_url + "?date=" + str(start_day)
                if start_time is not None:
                    uuid = uuid + "&hour=" + str(start_time)

                self.add_event_with_props(
                    default_values,
                    event_url,
                    title,
                    category,
                    start_day,
                    location,
                    description,
                    [],
                    recurrences=None,
                    uuids=[uuid],
                    url_human=event_url,
                    start_time=start_time,
                    end_day=end_day,
                    end_time=end_time,
                    published=published,
                    image=image,
                    image_alt=image_alt,
                )
