
import calendar
import locale
import random

from django.core.mail import send_mail, BadHeaderError, EmailMessage
from django.http import HttpResponse
from django.http import JsonResponse
from django.shortcuts import render, redirect
from calendar import HTMLCalendar
from datetime import date, timedelta, datetime
from reservation.models import Reservation, TarifSaison
from django.db.models import Q
from django.urls import reverse
from .forms import ReservationForm

# Constantes des couleurs pour le calendrier
SAISON_CREUSE_COLOR = "#b2eab2"
SAISON_NORMALE_COLOR = "#b2d8ff"
SAISON_HAUTE_COLOR = "#ffd9b2"
ATTENTE_DATE_COLOR = "#a97a4c"
CONFIRMED_DATE_COLOR = "red"


###########################################
# AFFICHAGE DU CALENDRIER DES RESERVATIONS
###########################################
def calendar_view(request, year, month):
     # Récupérer la date actuelle
    today = date.today()

    # Définir le premier et le dernier jour du mois
    start_month = date(year, month, 1)
    end_month = date(year, month, calendar.monthrange(year, month)[1])

    # Générer les semaines du calendrier
    cal = calendar.monthcalendar(year, month)
    weeks = []
    for week in cal:
        week_days = []
        for day in week:
            if day == 0:
                week_days.append(None)
            else:
                week_days.append(date(year, month, day))

        weeks.append(week_days)

    # Initialiser des dictionnaires pour stocker les dates de début et de fin des réservations en attente et confirmées,
    # les dates réservées et les tarifs saisonniers
    attente_start_dates = {}    
    attente_end_dates = {}
    confirmed_start_dates = {}    
    confirmed_end_dates = {}
    reserved_attente_dates = {}
    reserved_confirmed_dates = {}
    saison_creuse_dates = {}
    saison_normale_dates = {}
    saison_haute_dates = {}

    # Filtrer les réservations en attente et confirmées ayant lieu ce mois-ci
    attente_startend = Reservation.objects.filter(
        Q(etat_reservation='ATT') &
        (Q(date_arrivee__range=(start_month, end_month)) |
        Q(date_depart__range=(start_month, end_month)) |
        Q(date_arrivee__lte=start_month, date_depart__gte=end_month))
    )
    confirmed_startend = Reservation.objects.filter(
        Q(etat_reservation='CONF') &
        (Q(date_arrivee__range=(start_month, end_month)) |
        Q(date_depart__range=(start_month, end_month)) |
        Q(date_arrivee__lte=start_month, date_depart__gte=end_month))
    )

    # Filtrer les réservations en attente et confirmées ayant lieu ce mois-ci (en utilisant la méthode Q)
    reservations_attente = Reservation.objects.filter(
        Q(etat_reservation='ATT') & 
        ((Q(date_arrivee__month=month) & Q(date_arrivee__year=year)) |
        (Q(date_depart__month=month) & Q(date_depart__year=year)))
    )
    reservations_confirmed = Reservation.objects.filter(
        Q(etat_reservation='CONF') & 
        ((Q(date_arrivee__month=month) & Q(date_arrivee__year=year)) |
        (Q(date_depart__month=month) & Q(date_depart__year=year)))
    )

    # Filtrer les tarifs saisonniers pour la saison creuse, normale et haute de ce mois
    saison_creuse = TarifSaison.objects.filter(Q(nom_periode='SC') & (Q(date_debut__lte=start_month) | Q(date_fin__gte=end_month)))
    saison_normale = TarifSaison.objects.filter(Q(nom_periode='SN') & (Q(date_debut__lte=start_month) | Q(date_fin__gte=end_month)))
    saison_haute = TarifSaison.objects.filter(Q(nom_periode='SH') & (Q(date_debut__lte=start_month) | Q(date_fin__gte=end_month)))

    # Ajouter les dates de début et de fin des réservations en attente à leurs dictionnaires respectifs
    attente_start_dates = get_start_date(attente_startend, month, year)
    attente_end_dates = get_end_date(attente_startend, month, year)

    # Ajouter les dates de début et de fin des réservations confirmées à leurs dictionnaires respectifs
    confirmed_start_dates = get_start_date(confirmed_startend, month, year)
    confirmed_end_dates = get_end_date(confirmed_startend, month, year)

    # Ajouter les dates réservées pour les réservations en attente et confirmées à leurs dictionnaires respectifs
    reserved_attente_dates = get_reserved_date(reservations_attente, month, year)
    reserved_confirmed_dates = get_reserved_date(reservations_confirmed, month, year)
    
    # Ajouter les dates pour les saisons creuse, normale et haute à leurs dictionnaires respectifs
    saison_creuse_dates = get_saison_date(saison_creuse, month, year)
    saison_normale_dates = get_saison_date(saison_normale, month, year)
    saison_haute_dates = get_saison_date(saison_haute, month, year)
    
    # Génère l'URL pour le mois précédent en fonction des paramètres "year" et "month" passés en argument
    previous_month = prev_month_url(year, month)
    # Génère l'URL pour le mois suivant en fonction des paramètres "year" et "month" passés en argument
    next_month = next_month_url(year, month)
    # Récupère le nom du mois correspondant à l'entier "month" passé en argument en utilisant une fonction définie ailleurs dans le code
    month_name = get_month_name(month)
 
    # Render the template with the calendar weeks
    head_title = "Disponibilités de la Villa Route des Epices à l'ïle Maurice"
    return render(request, 'calendrier.html', {
        'head_title': head_title,
        'month': month,
        'month_name': month_name,
        'today': today,
        'weeks': weeks,
        'cal': cal,
        'year': year,
        'previous_month': previous_month,
        'next_month': next_month,
        'attente_start_dates': attente_start_dates,
        'attente_end_dates': attente_end_dates,
        'confirmed_start_dates': confirmed_start_dates,
        'confirmed_end_dates': confirmed_end_dates,
        'reserved_attente_dates': reserved_attente_dates,
        'reserved_confirmed_dates': reserved_confirmed_dates,
        'saison_creuse_dates': saison_creuse_dates,
        'saison_normale_dates': saison_normale_dates,
        'saison_haute_dates': saison_haute_dates,
        'saison_creuse_color': SAISON_CREUSE_COLOR,
        'saison_normale_color': SAISON_NORMALE_COLOR,
        'saison_haute_color': SAISON_HAUTE_COLOR,
        'attente_date_color': ATTENTE_DATE_COLOR,
        'confirmed_date_color': CONFIRMED_DATE_COLOR,
    })



########################################
# FORMULAIRE DE RESERVATION DE LA VILLA
########################################
def reserved_view(request):
    form = ReservationForm()
    if request.method == 'POST':
        form = ReservationForm(request.POST)
        if form.is_valid():
            form.save()
            nom = form.cleaned_data['nom']
            prenom = form.cleaned_data['prenom']
            adresse = form.cleaned_data['adresse']
            code_postal = form.cleaned_data['code_postal']
            ville = form.cleaned_data['ville']
            email = form.cleaned_data['email']
            telephone = form.cleaned_data['telephone']
            date_arrivee = form.cleaned_data['date_arrivee']
            date_depart = form.cleaned_data['date_depart']

            email_body = """
                <html>
                <head></head>
                <body>
                    <div style="font-size:20px; font-weight:bold; text-decoration:underline; margin-bottom:20px">Formulaire de demande de Réservation</div>
                    <div style="display:flex; flex-wrap:nowrap; margin-bottom:10px">
                        <div style="font-size:14px; font-weight:bold;">Nom :&nbsp;</div><div style="font-size:14px">%s</div>
                    </div>
                    <div style="display:flex; flex-wrap:nowrap; margin-bottom:10px">
                        <div style="font-size:14px; font-weight:bold;">Prénom :&nbsp;</div><div style="font-size:14px">%s</div>
                    </div>
                    <div style="display:flex; flex-wrap:nowrap; margin-bottom:10px">
                        <div style="font-size:14px; font-weight:bold;">Adresse :&nbsp;</div><div style="font-size:14px">%s</div>
                    </div>
                    <div style="display:flex; flex-wrap:nowrap; margin-bottom:10px">
                        <div style="font-size:14px; font-weight:bold;">Code postal :&nbsp;</div><div style="font-size:14px">%s</div>
                    </div>
                    <div style="display:flex; flex-wrap:nowrap; margin-bottom:10px">
                        <div style="font-size:14px; font-weight:bold;">Ville :&nbsp;</div><div style="font-size:14px">%s</div>
                    </div>
                    <div style="display:flex; flex-wrap:nowrap; margin-bottom:10px">
                        <div style="font-size:14px; font-weight:bold;">Email :&nbsp;</div><div style="font-size:14px">%s</div>
                    </div>
                    <div style="display:flex; flex-wrap:nowrap; margin-bottom:10px">
                        <div style="font-size:14px; font-weight:bold;">Téléphone :&nbsp;</div><div style="font-size:14px">%s</div>
                    </div>
                    <div style="display:flex; flex-wrap:nowrap; margin-bottom:10px">
                        <div style="font-size:14px; font-weight:bold;">Date d'arrivée :&nbsp;</div><div style="font-size:14px">%s</div>
                    </div>
                    <div style="display:flex; flex-wrap:nowrap; margin-bottom:10px">
                        <div style="font-size:14px; font-weight:bold;">Date de départ :&nbsp;</div><div style="font-size:14px">%s</div>
                    </div>
                </body>
                </html>
                """ % (nom, prenom, adresse, code_postal, ville, email, telephone, date_arrivee, date_depart)

            sujet = "Nouvelle réservation sur www.ile-maurice-location.com"
            try:
                demand = EmailMessage(sujet, email_body, 'no-reply@ile-maurice-location.com', to=['christianbab1@orange.fr'], bcc=['contact@marzat-informatique.com'])
                demand.content_subtype = "html" # this is the crucial part
                demand.send()
                demand = EmailMessage(sujet, email_body, 'no-reply@ile-maurice-location.com', to=[email])
                demand.content_subtype = "html" # this is the crucial part
                demand.send()
            except BadHeaderError:
                return HttpResponse('Invalid header found.')
            return redirect('confirmation_reservation')
    else:
        form = ReservationForm()

    month = date.today().month
    year = date.today().year

    head_title = "Réservez la villa Route des Epîces à l'Ile Maurice"
    context = {
        'head_title': head_title,
        'form': form,
        'year': year,
        'month': month,
    }
    return render(request, 'demande_location_villa.html', context)


#################################
# CONFIRMATION DE LA RESERVATION
#################################
def confirmation_reservation_view(request):
    head_title = ""

    month = date.today().month
    year = date.today().year

    return render(request, 'confirmation_reservation.html', {
        'head_title': head_title,
        'year': year,
        'month': month,
    })




###############################
# FONCTIONS POUR LE TRAITEMENT
###############################


def daterange(start_date, end_date):
    for n in range(int((end_date - start_date).days) + 1):
        yield start_date + timedelta(n)


def prev_month_url(year, month):
    # Cette fonction retourne l'URL pour le mois précédent.
    prev_month = (datetime(year, month, 1) - timedelta(days=1)).replace(day=1)
    return reverse('calendrier', kwargs={'year': prev_month.year, 'month': prev_month.month})


def next_month_url(year, month):
    # Cette fonction retourne l'URL pour le mois suivant.
    next_month = (datetime(year, month, 28) + timedelta(days=4)).replace(day=1)
    return reverse('calendrier', kwargs={'year': next_month.year, 'month': next_month.month})


def get_month_name(month_number):
    # Définir la locale actuelle
    locale.setlocale(locale.LC_TIME, '')
    # Obtenir le nom du mois dans la langue locale
    month_name = calendar.month_name[month_number]
    return month_name.capitalize()


def get_saison_date(saison, month, year):
    saison_dates = {}

    for tarif in saison:
        for single_date in daterange(tarif.date_debut, tarif.date_fin):
            if (single_date.month == month) & (single_date.year == year):
                saison_dates[single_date.day] = True

    return saison_dates


def get_start_date(dates, month, year):
    start_date = {}

    for reservation in dates:
        if (reservation.date_arrivee.month == month) & (reservation.date_arrivee.year == year): 
            start_date[reservation.date_arrivee.day] = True

    return start_date


def get_end_date(dates, month, year):
    end_date = {}

    for reservation in dates:
        if (reservation.date_depart.month == month) & (reservation.date_depart.year == year):
            end_date[reservation.date_depart.day] = True

    return end_date


def get_reserved_date(dates, month, year):
    reserved_dates = {}

    for reservation in dates:
        for single_date in daterange(reservation.date_arrivee, reservation.date_depart):
            if (single_date.month == month) & (single_date.year == year):
                reserved_dates[single_date.day] = True

    return reserved_dates


def ajax_valid_dates(request):
    date_arrivee = datetime.strptime(request.POST['date_arrivee'], '%Y-%m-%d').date()
    date_depart = datetime.strptime(request.POST['date_depart'], '%Y-%m-%d').date()

    result = (date_depart - date_arrivee).days

    reserved_date = Reservation.objects.filter(date_arrivee__lt=date_depart, date_depart__gt=date_arrivee)
    if reserved_date.exists():
        reserved = True
    else:
        reserved = False

    return JsonResponse({'valid': result, 'reserved': reserved})