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

# A class dedicated to get events from Cinéma Le Rio (Clermont-Ferrand)
# URL: https://www.cinemalerio.com/evenements/
class CExtractor(TwoStepsExtractorNoPause):

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

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

        links = soup.select("td.seance_link a")
        if links:
            for l in links:
                self.add_event_url(l["href"])

    def to_text_select_one(soup, filter):
        e = soup.select_one(filter)
        if e is None:
            return None
        else:
            return e.text

    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

        alerte_date = CExtractor.to_text_select_one(soup, ".alerte_date")
        if alerte_date is None:
            return
        dh = alerte_date.split("à")
        # if date is not found, we skip
        if len(dh) != 2:            
            return
        
        date = Extractor.parse_french_date(dh[0], default_year=datetime.now().year)
        time = Extractor.parse_french_time(dh[1])

        synopsis = CExtractor.to_text_select_one(soup, ".synopsis_bloc")
        special_titre = CExtractor.to_text_select_one(soup, ".alerte_titre")
        special = CExtractor.to_text_select_one(soup, ".alerte_text")

        # it's not a specific event: we skip it
        special_lines = None if special is None else special.split('\n')
        if special is None or len(special_lines) == 0 or \
            (len(special_lines) == 1 and special_lines[0].strip().startswith('En partenariat')):
            return

        description = "\n\n".join([x for x in [synopsis, special_titre, special] if not x is None])

        image = soup.select_one(".col1 img")
        image_alt = None
        if not image is None:
            image_alt = image["alt"]
            image = image["src"]

        self.add_event_with_props(
                    default_values,
                    event_url,
                    title,
                    None,
                    date,
                    None,
                    description,
                    [],
                    recurrences=None,
                    uuids=[event_url],
                    url_human=event_url,
                    start_time=time,
                    end_day=None,
                    end_time=None,
                    published=published,
                    image=image,
                    image_alt=image_alt
                )