from datetime import date, timedelta

from django.http import (
    HttpResponseRedirect,
)
from django.shortcuts import render
from django.urls import reverse_lazy
from django.utils.timezone import datetime

from .utils import get_event_qs
from ..calendar import CalendarMonth, CalendarWeek, CalendarList
from ..filters import EventFilter
from ..models import Category


def day_view(request, year=None, month=None, day=None, cat=None):
    if year is None or month is None or day is None:
        if "when" in request.POST:
            when = datetime.strptime(request.POST["when"], "%Y-%m-%d")
            year = when.year
            month = when.month
            day = when.day

            request = EventFilter.set_default_values(request)
            qs = get_event_qs(request).select_related("exact_location")
            if cat is not None:
                category = Category.objects.filter(slug=cat).first()
                qs = qs.filter(category=category)
            else:
                category = None
            filter = EventFilter(request.GET, qs, request=request)

            return HttpResponseRedirect(
                reverse_lazy("day_view", args=[year, month, day])
                + "?"
                + filter.get_url()
            )

    return upcoming_events(request, year, month, day, 0, cat)


def month_view(request, year=None, month=None, cat=None):
    now = date.today()
    if year is None and month is None:
        day = now.day
    else:
        day = None
    if year is None:
        year = now.year
    if month is None:
        month = now.month

    request = EventFilter.set_default_values(request)
    qs = get_event_qs(request).only(
        "title",
        "start_day",
        "start_time",
        "category",
        "other_versions",
        "recurrences",
        "end_day",
        "end_time",
        "uuids",
        "status",
        "tags",
    )
    if cat is not None:
        category = Category.objects.filter(slug=cat).first()
        qs = qs.filter(category=category)
    else:
        category = None

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

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

    cmonth = CalendarMonth(year, month, filter, day=day)

    context = {
        "calendar": cmonth,
        "this_month": day is not None,
        "filter": filter,
        "category": category,
        "init_date": now if cmonth.today_in_calendar() else cmonth.firstdate,
    }
    return render(request, "agenda_culturel/page-month.html", context)


def week_view(request, year=None, week=None, home=False, cat=None):
    now = date.today()
    if year is None:
        year = now.isocalendar()[0]
    if week is None:
        week = now.isocalendar()[1]

    request = EventFilter.set_default_values(request)
    qs = (
        get_event_qs(request)
        .select_related("exact_location")
        .only(
            "title",
            "start_day",
            "start_time",
            "category",
            "other_versions",
            "recurrences",
            "end_day",
            "end_time",
            "uuids",
            "status",
            "tags",
            "local_image",
            "image",
            "image_alt",
            "exact_location",
            "description",
        )
    )
    if cat is not None:
        category = Category.objects.filter(slug=cat).first()
        qs = qs.filter(category=category)
    else:
        category = None
    filter = EventFilter(request.GET, qs, request=request)

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

    cweek = CalendarWeek(year, week, filter)

    context = {
        "year": year,
        "week": week,
        "calendar": cweek,
        "filter": filter,
        "category": category,
        "init_date": now if cweek.today_in_calendar() else cweek.firstdate,
    }
    if home:
        context["home"] = 1
    return render(request, "agenda_culturel/page-week.html", context)


def upcoming_events(request, year=None, month=None, day=None, neighsize=1, cat=None):
    now = date.today()
    if year is None:
        year = now.year
    if month is None:
        month = now.month
    if day is None:
        day = now.day

    day = date(year, month, day)
    day = day + timedelta(days=neighsize)

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

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

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

    cal = CalendarList(
        day + timedelta(days=-neighsize),
        day + timedelta(days=neighsize),
        filter,
        True,
    )

    context = {
        "calendar": cal,
        "now": now,
        "day": day,
        "init_date": now if cal.today_in_calendar() else day,
        "filter": filter,
        "date_pred": day + timedelta(days=-neighsize - 1),
        "date_next": day + timedelta(days=neighsize + 1),
        "category": category,
    }

    return render(request, "agenda_culturel/page-upcoming.html", context)
