import json

from django.http import HttpResponse, JsonResponse, HttpResponseRedirect
from django.http import FileResponse
from django.shortcuts import render
from django.views import generic
from django.template import loader
from django.views.decorators.clickjacking import xframe_options_exempt
from django.contrib.auth.decorators import login_required
from django.db.models import Q


import caldav as cal

from datetime import datetime, timedelta, time
from django.shortcuts import redirect

# Create your views here.

from mycaldav.models import *
from mycaldav.settings import *
from mycaldav.export_team_pdf import *
from comm_op.models import comm_opMessage


from rest_framework.response import Response
from rest_framework import status
from rest_framework.decorators import api_view

from mycaldav.models import CalDavItemSerializer, _caldav_item
from mycaldav.settings import CALDAV_URL,CALDAV_USER,CALDAV_PASSWORD

import logging

logger = logging.getLogger(__name__)


def formatResponseArray(o_caldav, inverted=False):
    
    try:
        if inverted:
            o_caldav.items.reverse()
            o_caldav.day.reverse()
            o_caldav.night.reverse()

        # Serialize data
        serializer_items = CalDavItemSerializer(data=[item.__dict__ for item in o_caldav.items], many=True)
        serializer_day = CalDavItemSerializer(data=[item.__dict__ for item in o_caldav.day], many=True)
        serializer_night = CalDavItemSerializer(data=[item.__dict__ for item in o_caldav.night], many=True)

        # Check validation and print errors
        validate_and_log(serializer_items, "items")
        validate_and_log(serializer_day, "day")
        validate_and_log(serializer_night, "night")

        response_data = {
            "items": serializer_items.data,
            "day": serializer_day.data,
            "night": serializer_night.data,
        }
        response_status = status.HTTP_200_OK

    except Exception as e:
        logger.error(f"An error occurred: {e}")
        response_data = {"error": "An error occurred while processing the request."}
        response_status = status.HTTP_500_INTERNAL_SERVER_ERROR

    return {"data":response_data, "status": response_status}
def validate_and_log(serializer, label):
    if not serializer.is_valid():
        print(f"Validation Error {label}: {serializer.errors}")
@api_view(['GET'])
def view_task_caldav(request):
    o_caldav = cls_caldav(url=caldav_cfg["task"])
    o_caldav.get_caldav_data()    
    '''
    o_caldav_sync_management = caldav_sync_manager()
    o_caldav_sync_management.init_caldav(caldav_url=CALDAV_URL, caldav_user=CALDAV_USER, caldav_password=CALDAV_PASSWORD)
    o_caldav_sync_management.init_task_management()
    '''
   

    response = formatResponseArray(o_caldav)
    return Response(response["data"], status=response["status"])



@api_view(['POST'])
def view_task_edit_caldav(request):    
    data = request.data
    uuid = data.get('uuid', None)
    if uuid is None:
        # Gérer le cas où l'UUID n'est pas fourni dans les données JSON
        return JsonResponse({'error': 'UUID non fourni dans les données JSON'}, status=400)
    
    myClient = cls_caldav_client()
    myClient.init_caldav(caldav_url=CALDAV_URL, caldav_user=CALDAV_USER, caldav_password=CALDAV_PASSWORD)
    myClient.mark_as_done_task(calandar=myClient.a_task,uuid=uuid)    
    return JsonResponse({'sucsess': 'UUID marqué à done'}, status=200)
    
    

@api_view(['POST'])
def view_op_edit_caldav(request):
    data = json.loads(request.body.decode('utf-8'))
    uuid = data.get('uuid', None)
    if uuid is None:
        # Gérer le cas où l'UUID n'est pas fourni dans les données JSON
        return JsonResponse({'error': 'UUID non fourni dans les données JSON'}, status=400)
    object = comm_opMessage.objects.get(pk=uuid)
    object.bDone = True
    object.dtEnd = datetime.today()
    object.save()

    return JsonResponse({'sucsess': 'UUID marqué à done'}, status=200)
@api_view(['POST'])
def view_vhc_edit_caldav(request):
    data = request.data
    uuid = data.get('uuid', None)
    if uuid is None:
        # Gérer le cas où l'UUID n'est pas fourni dans les données JSON
        return JsonResponse({'error': 'UUID non fourni dans les données JSON'}, status=400)
    myClient = cls_caldav_client()
    myClient.init_caldav(caldav_url=CALDAV_URL, caldav_user=CALDAV_USER, caldav_password=CALDAV_PASSWORD)
    myClient.mark_as_done_task(calandar=myClient.a_vhc,uuid=uuid)
    return JsonResponse({'sucsess': 'UUID marqué à done'}, status=200)

@api_view(['GET'])
def view_vhc_caldav(request):
        o_caldav = cls_caldav(url=caldav_cfg["vhc"])
        o_caldav.get_caldav_data(periode=2)

        response = formatResponseArray(o_caldav)
        return Response(response["data"], status=response["status"])

@api_view(['GET'])
def view_rh_caldav(request):
    o_caldav = cls_caldav(url=caldav_cfg["rh"])
    o_caldav.get_caldav_data(periode=2)

    response = formatResponseArray(o_caldav,inverted=False)
    return Response(response["data"], status=response["status"])



@api_view(['GET'])
def view_road_caldav(request):
    o_caldav = cls_caldav(url=caldav_cfg["road"])
    o_caldav.get_caldav_data(periode=2)
    response = formatResponseArray(o_caldav, inverted=True)
    return Response(response["data"], status=response["status"])


def close_old_op_message():
    old_items = comm_opMessage.objects.filter(bDone=False, dtEnd__lte=datetime.today() - timedelta(days=1))
    for old_item in old_items:
        old_item.bDone = True
        old_item.save()

@api_view(['GET'])
def view_op_caldav(request):
    close_old_op_message()

    o_items = comm_opMessage.objects.filter(Q(dtStart__lte= datetime.today() + timedelta(days=1)) & ( Q(dtEnd__gte=datetime.today()) | Q(dtEnd__isnull=True)))
    all_items = []
    for item in o_items:
        temp_item = _caldav_item()
        temp_item.uuid = f"{item.uuid}"
        temp_item.name = item.sTitle
        temp_item.desc = item.sDesc
        temp_item.key = item.sKey
        temp_item.done = item.bDone
        temp_item.str_start_date = str(item.dtStart.strftime('%d')) + "." + str(item.dtStart.strftime('%m'))
        if item.dtEnd != None:
            temp_item.str_end_date = str(item.dtEnd.strftime('%d')) + "." + str(item.dtEnd.strftime('%m'))
        else:
            temp_item.str_end_date = None
        all_items.append(temp_item)

    try:
        serializer = CalDavItemSerializer(data=all_items, many=True)
        if serializer.is_valid():
            print("Serialized Data:", serializer.data)
        else:
            print("Validation Error:", serializer.errors)

    except Exception as e:
        logger.error(f"An error occurred: {e}")
        return Response({"error": "An error occurred while processing the request."},
                        status=status.HTTP_500_INTERNAL_SERVER_ERROR)
    return Response({"items":serializer.data})

@api_view(['GET'])
def view_team_caldav(request):
    #Change timezone
   

    o_caldav = cls_caldav(url=caldav_cfg["team"])
    o_caldav.get_caldav_data(periode=3)
    template = loader.get_template("team/team_view.html")
    o_caldav.sort_array_by_key(False)

    response = formatResponseArray(o_caldav)
    additional_data = {
        'today': datetime.today().strftime('%d.%m'),
        'yesterday': (datetime.today() + timedelta(days=-1)).strftime('%d.%m'),
        'tomorrow': (datetime.today() + timedelta(days=1)).strftime('%d.%m')
    }
    response["data"].update(additional_data)
    return Response(response["data"], status=response["status"])


@api_view(['GET'])
def view_manif_caldav(request):
    o_caldav = cls_caldav(url=caldav_cfg["manif"])
    o_caldav.get_caldav_data(periode=1)
    o_caldav.sort_array_by_key(True)

    response = formatResponseArray(o_caldav)
    return Response(response["data"], status=response["status"])


@xframe_options_exempt
def view_team_pdf_caldav(request):
    o_caldav = cls_caldav(url=caldav_cfg["team"])
    if not "dt" in request.GET.keys():
        start = datetime.today()
    else:
        start = datetime.strptime(request.GET['dt'], "%d.%m.%Y")

    myClient = cls_caldav_client()
    myClient.init_caldav(caldav_url=CALDAV_URL, caldav_user=CALDAV_USER, caldav_password=CALDAV_PASSWORD)
    render_pdf(o_caldav, caldavClient=myClient, date=start)
    return  FileResponse(open('mycaldav/export.pdf', 'rb'), as_attachment=False, content_type='application/pdf')




@xframe_options_exempt
@login_required
def view_reskreen(request):
    template = loader.get_template("reskreen.html")
    #context = {'latest_task_list': o_caldav.day, 'night_task_list': o_caldav.night, 'today': datetime.today().strftime('%d.%m')}
    context = {}
    return HttpResponseRedirect('https://reskreen.ambulance-clerc.ch')

from django_autologin.templatetags.django_autologin import automatic_login_token
@login_required
def view_generate_token(request):
    current_user = request.user
    auto_login = automatic_login_token(current_user)
    print(f"{current_user.username} autologin=> {auto_login}")
    return HttpResponse(f"{current_user.username}autologin=> {auto_login}")


