from ..extractor import *
import json
from bs4 import BeautifulSoup
from urllib.parse import urlparse, unquote
import pytz
import html


# A class dedicated to get events from les amis du temps des cerises
# Website https://amisdutempsdescerises.org/
class CExtractor(Extractor):

    def __init__(self):
        super().__init__()
        self.data = b'------toto\r\nContent-Disposition: form-data; name="p"\r\n\r\nfutur\r\n------toto--\r\n'
        self.content_type = 'multipart/form-data; boundary=----toto'


    def extract(
        self, content, url, url_human=None, default_values=None, published=False
    ):
        self.set_header(url)
        self.clear_events()

        root_url = "https://" + urlparse(url).netloc + "/"
        images_basename = root_url + "images/"
        from_timezone = pytz.utc
        to_timezone = pytz.timezone("Europe/Paris")

        events = json.loads(content)
        for e in events:
            tags = []
            start_day = e["ev_date"].split(' ')[0]
            start_time = e["ev_time"]
            title = html.unescape(e["ev_titre"])
            if "ev_sstitre" in e and e["ev_sstitre"] != '':
                title = title + ' - ' + html.unescape(e["ev_sstitre"])

            soup = BeautifulSoup(e["ev_info"], "html.parser")
            description = soup.text
            location = html.unescape(e["li_nom"]) if "li_nom" in e else None
            if "ev_canceled" in e and e["ev_canceled"] != '0':
                tags += ["annulé"]

            image = None
            if "ev_img" in e and e["ev_img"] != '':
                image = images_basename + e["ev_img"]
            
            naive_dt = datetime.strptime(e["ev_date"], "%Y-%m-%d %H:%M:%S")

            from_dt = from_timezone.localize(naive_dt)
            dt = to_timezone.normalize(from_dt)
            ts = int(datetime.timestamp(dt)) * 1000
                        
            event_url = root_url + "#" + str(ts)

            self.add_event(
                default_values,
                title,
                None,
                start_day,
                location,
                description,
                tags,
                uuids=[event_url],
                recurrences=None,
                url_human=event_url,
                start_time=start_time,
                published=published,
                image=image )             
        
        return self.get_structure()
