from ..twosteps_extractor import *
from bs4 import BeautifulSoup
from datetime import datetime, date

# 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

    # this method is not perfect, but dates and hours are not structured
    def parse_dates(self, date):
        dl = date.replace(' à ', '\n').split('\n')
        result = []

        for d in dl:
            # only lines with a digit
            if sum(c.isdigit() for c in d) != 0:
                # split subparts
                for d2 in d.replace(' et ', ', ').split(', '):
                    d2 = d2.strip()
                    dd = Extractor.parse_french_date(d2, default_year_by_proximity=self.today)
                    if dd is None:
                        hh = Extractor.parse_french_time(d2)
                        for i, r in enumerate(result):
                            result[i][1].append(hh)
                    else: 
                        result.append([dd, []])

        if "De" in date and " à " in date:
            for i, r in enumerate(result):
                result[i].append(True)

        return result

    def build_event_url_list(self, content, infuture_days=180):
        
        soup = BeautifulSoup(content, "html.parser")
        links = soup.select('.cell a.evenement')
        for l in links:
            self.add_event_url(self.root_address + l["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 not soustitre is None:
            soustitre = soustitre.text.strip()

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

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

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


        date = soup.select_one('.champ.date-libre').text

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

        if " au " in date or date.startswith("Du") or date.lower().strip() == "en continu" or date.startswith("Les"):
            return
        
        dates = self.parse_dates(date)
        end_day = None

        for d in dates:
            if len(d) >= 2:
                start_day = d[0]

                if len(d) == 3 and len(d[1]) == 2:
                    start_time = d[1][0]
                    end_time = d[1][1]
                    uuid = event_url + "?date=" + str(start_day) + "&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=start_day,
                                end_time=end_time,
                                published=published,
                                image=image,
                                image_alt=image_alt
                            )
                else:
                    end_time = None
                    if len(d[1]) == 0:
                        start_time = None
                        uuid = event_url + "?date=" + str(start_day)
                        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=start_day,
                                    end_time=end_time,
                                    published=published,
                                    image=image,
                                    image_alt=image_alt
                                )
                    for t in d[1]:
                        start_time = t
                        uuid = event_url + "?date=" + str(start_day) + "&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=start_day,
                                    end_time=end_time,
                                    published=published,
                                    image=image,
                                    image_alt=image_alt
                                )

