from ..twosteps_extractor import *
from .fbevent import FacebookEvent
import json5
from bs4 import BeautifulSoup
import json
import os
from datetime import datetime
from django.utils.translation import gettext_lazy as _


import logging

logger = logging.getLogger(__name__)


# A class dedicated to get events from a facebook events page
# such as https://www.facebook.com/laJeteeClermont/events
class CExtractor(TwoStepsExtractor):

    def __init__(self):
        super().__init__()
        self.has_2nd_method_in_list = True

    def find_event_id_fragment_in_array(self, array):
        found = False
        if isinstance(array, dict):
            if "__typename" in array and array["__typename"] == "Event" and "id" in array:
                self.add_event_url("https://www.facebook.com/events/" + array["id"] + "/")
                self.found = True
            else:
                for k in array:
                    if k == "pageItems":
                        self.has_page_items = True
                    self.find_event_id_fragment_in_array(array[k])
        elif isinstance(array, list):
            for e in array:
                self.find_event_id_fragment_in_array(e)


    def find_in_js(self, soup):

        for json_script in soup.find_all("script", type="application/json"):
            json_txt = json_script.get_text()
            json_struct = json.loads(json_txt)
            self.find_event_id_fragment_in_array(json_struct)


    def prepare_2nd_extract_in_list(self):
        FacebookEventExtractor.prepare_2nd_extract_dler(self.downloader)


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

        debug = True

        self.found = False
        links = soup.find_all("a")
        for link in links:
            href = link.get('href')
            if not href is None and href.startswith('https://www.facebook.com/events/'):
                self.add_event_url(href.split('?')[0])
                self.found = True

        self.has_page_items = False
        self.find_in_js(soup)


        if not self.found:
            logger.warning("cannot find any event link in events page. Save content page")
            if debug:
                CExtractor.dump_content_for_debug(content, self.url)

        if not self.has_page_items:
            raise Exception(_("the page was not yet populated with events, so the loading time was probably too short"))


    def dump_content_for_debug(content, url):
        directory = "errors/"
        if not os.path.exists(directory):
            os.makedirs(directory)
        now = datetime.now()
        filename = directory + now.strftime("%Y%m%d_%H%M%S") + ".html"
        with open(filename, "w") as text_file:
            text_file.write("<!-- " + url + " -->\n\n")
            text_file.write(content)

                


    def add_event_from_content(
        self,
        event_content,
        event_url,
        url_human=None,
        default_values=None,
        published=False,
    ):
        debug = True

        fevent = None
        soup = BeautifulSoup(event_content, "html.parser")
        for json_script in soup.find_all("script", type="application/json"):
            json_txt = json_script.get_text()
            json_struct = json.loads(json_txt)
            fevent = FacebookEvent.find_event_fragment_in_array(
                json_struct, fevent
            )

        if fevent is not None:
            for event in fevent.build_events(event_url):
                event["published"] = published

                # only add the event if its unknown
                if len([e for e in self.events if event["uuids"][0] in e["uuids"]]) == 0:
                    self.add_event(default_values, **event)
        else:
            if debug:
                CExtractor.dump_content_for_debug(event_content, event_url)
            raise Exception(
                        _("Cannot get Facebook event from {}").format(event_url)
                    )


