import logging
from datetime import datetime, timedelta
from django.conf import settings
import dateutil.parser
import requests
from bs4 import BeautifulSoup

from ..extractor import Extractor

logger = logging.getLogger(__name__)


# A class dedicated to get events from echosciences
class CExtractor(Extractor):
    events_api = "/open_api/v1/events"
    event_api = "/open_api/v1/events/"

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

    def token_available(self):
        return settings.ECHOSCIENCES_TOKEN != ""

    def _get_data(self, url, params={}):
        headers = {"Authorization": "Token token=" + settings.ECHOSCIENCES_TOKEN}

        response = requests.get(
            url=url,
            json=params,
            headers=headers,
        )

        if response.status_code == 200:
            response_json = response.json()
            if "errors" in response_json:
                raise Exception(
                    f"Errors while requesting {url}. {str(response_json['error'])}"
                )

            return response_json
        else:
            raise Exception(
                f"Error while requesting. Status code: {response.status_code}"
            )

    def _oncoming_events(self, url):
        result = []

        for i in range(1, 200):
            r = self._get_data(
                url + CExtractor.events_api,
                {
                    "per_page": 20,
                    "page": i,
                    "order_by": "start_date",
                    "order_type": "asc",
                    "start_date": datetime.today().strftime("%Y-%m-%d"),
                    "end_date": (datetime.today() + timedelta(weeks=30)).strftime(
                        "%Y-%m-%d"
                    ),
                },
            )
            if len(r) == 0:
                break
            result = result + r

        return result

    def _get_event(self, url, slug):
        return self._get_data(url + CExtractor.event_api + slug)

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

        self.set_header(url)
        self.clear_events()

        if not self.token_available():
            raise Exception("Token not available")

        events = self._oncoming_events(url)

        for e in events:
            event = self._get_event(url, e["slug"])

            title = event["name"]
            event_url = event["url"]
            image = event["image"]["url"]

            location = []
            if "place" in event and event["place"] is not None:
                location.append(event["place"]["name"])
            location.append(event["address"])
            location = ", ".join(location)
            soup = BeautifulSoup(event["body"], "html.parser")

            description = soup.get_text()
            start = dateutil.parser.isoparse(event["start_date"])
            end = dateutil.parser.isoparse(event["end_date"])

            start_day = start.date()
            start_time = start.time()
            end_day = end.date()
            end_time = end.time()

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

        return self.get_structure()
