from ..twosteps_extractor import *
from bs4 import BeautifulSoup

# A class dedicated to get events from Arachnée Concert
# URL: https://www.arachnee-concerts.com/agenda-des-concerts/
class CExtractor(TwoStepsExtractorNoPause):

    def __init__(self):
        super().__init__()
        self.possible_dates = {}
        self.theater = None

    def extract(
        self,
        content,
        url,
        url_human=None,
        default_values=None,
        published=False,
        only_future=True,
        ignore_404=True
    ):
        match = re.match(r".*\&theatres=([^&]*)&.*", url)
        if match:
            self.theater = match[1]

        return super().extract(content, url, url_human, default_values, published, only_future, ignore_404)

    def build_event_url_list(self, content, infuture_days=180):
        
        soup = BeautifulSoup(content, "html.parser")

        containers = soup.select("ul.event_container>li")
        if containers:
            for c in containers:
                d = Extractor.parse_french_date(c.select_one(".date").text)
                l = c.select_one(".event_auditory").text
                if (self.theater is None or (l.startswith(self.theater))) and d < datetime.date.today() + timedelta(days=infuture_days):
                    t = Extractor.parse_french_time(c.select_one(".time").text)
                    e_url = c.select_one(".info a")["href"]
                    if not e_url in self.possible_dates:
                        self.possible_dates[e_url] = []
                    self.possible_dates[e_url].append((str(d) + " " + str(t)))
                    self.add_event_url(e_url)

    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 = ", ".join([x.text for x in [soup.select_one(y) for y in [".page_title", ".artiste-subtitle"]] if x])
        
        image = soup.select_one(".entry-image .image_wrapper img")
        if not image is None:
            image = image["src"]

        descs = soup.select(".entry-content p")
        if descs:
            description = "\n".join([d.text for d in descs])
        else:
            description = None

        category = soup.select_one(".event_category").text
        first_cat = Extractor.remove_accents(category.split(",")[0].lower())
        tags = []
        if first_cat in ["grand spectacle"]:
            category = "Spectacles"
            tags.append("💃 danse")
        elif first_cat in ["theatre", "humour / one man show"]:
            category = "Spectacles"
            tags.append("🎭 théâtre")
        elif first_cat in ["chanson francaise", "musique du monde", "pop / rock", "rap", "rnb", "raggae", "variete"]:
            category = "Fêtes & Concerts"
            tags.append("🎵 concert")
        elif first_cat in ["comedie musicale", "humour / one man show", "spectacle equestre"]:
            category = "Spectacles"
        elif first_cat in ["spectacle pour enfant"]:
            tags = ["🎈 jeune public"]
            category = None
        else:
            category = None

        dates = soup.select("#event_ticket_content>ul>li")
        for d in dates:
            dt = datetime.datetime.fromisoformat(d.select_one(".date")["content"])
            date = dt.date()
            time = dt.time()
            if str(date) + " " + str(time) in self.possible_dates[event_url]:
                location = d.select_one(".event_auditory").text
                
                self.add_event_with_props(
                    default_values,
                    event_url,
                    title,
                    category,
                    date,
                    location,
                    description,
                    tags,
                    recurrences=None,
                    uuids=[event_url + "?d=" + str(date) + "&t=" + str(time)],
                    url_human=event_url,
                    start_time=time,
                    end_day=None,
                    end_time=None,
                    published=published,
                    image=image,
                )
