import hashlib
from datetime import timedelta, date

import emoji
from django.core.cache import cache

from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import get_object_or_404

from . import get_event_qs
from ..calendar import CalendarList
from ..filters import EventFilter
from ..models import Event, Category, Place, Organisation, SiteConfiguration


def export_event_ical(request, year, month, day, pk):
    event = get_object_or_404(Event, pk=pk)
    event = event.get_recurrence_at_date(year, month, day)

    events = list()
    events.append(event)

    cal = Event.export_to_ics(events, request)

    response = HttpResponse(content_type="text/calendar")
    response.content = cal.to_ical().decode("utf-8").replace("\r\n", "\n")
    response["Content-Disposition"] = "attachment; filename={0}{1}".format(
        event.title.replace("\n", " ").replace("\r", "")[0:32], ".ics"
    )

    return response


def export_ical(request, cat=None, tag=None, organisation_pk=None, place_pk=None):
    now = date.today()

    qs = get_event_qs(request)
    if cat is not None:
        category = Category.objects.filter(slug=cat).first()
        qs = qs.filter(category=category)
    else:
        category = None

    if place_pk is not None:
        qs = qs.filter(exact_location=place_pk)
    if organisation_pk is not None:
        qs = qs.filter(organisers__in=[organisation_pk])
    if tag is not None:
        qs = qs.filter(tags__contains=[tag])

    request = EventFilter.set_default_values(request)
    filter = EventFilter(request.GET, queryset=qs, request=request)

    if filter.has_category_parameters():
        return HttpResponseRedirect(filter.get_new_url())

    id_cache = hashlib.md5(
        (
            filter.get_url()
            + "-"
            + str(tag)
            + "-"
            + str(cat)
            + "-"
            + str(organisation_pk)
            + "-"
            + str(place_pk)
        ).encode("utf8")
    ).hexdigest()
    ical = cache.get(id_cache)
    if not ical:
        calendar = CalendarList(
            now + timedelta(days=-7), now + timedelta(days=+60), filter
        )
        ical = calendar.export_to_ics(request)
        cache.set(id_cache, ical, 3600)  # 1 heure

    response = HttpResponse(content_type="text/calendar")
    response.content = ical.to_ical().decode("utf-8").replace("\r\n", "\n")
    extra = filter.to_str(" ")
    if extra is None:
        extra = ""
    if category is not None:
        extra += " " + str(category)
    if place_pk is not None:
        extra += (
            " @ " + Place.objects.filter(pk=place_pk).values("name").first()["name"]
        )
    if organisation_pk is not None:
        extra += (
            " - "
            + Organisation.objects.filter(pk=organisation_pk)
            .values("name")
            .first()["name"]
        )
    if tag is not None:
        extra += " - " + emoji.replace_emoji(tag, replace="")

    response["Content-Disposition"] = "attachment; filename={0}{1}{2}".format(
        SiteConfiguration.get_solo().site_name, extra, ".ics"
    )

    return response
