import asyncio
from datetime import date, datetime
from requests import Response
from management.models.base import GenericResponseObject
from management.models.commessa import Commessa, RisorseCommessa
from management.models.user import User
from management.models.vacations import Vacations
from management.repositories import UserRepository, PresenceRepository
from management.serializer import GenericResponseObjectSerializer
from management.utils.error_handling import GenericError, handle_exception
from management.utils.graph import get_group_members
from management.utils.graph import get_clients_cron
from management.models.clients import Cliente
from datetime import timedelta
import os
from django.db import transaction

def refresh_users():

    _repository = UserRepository()

    try:
        # User.objects.all().update(enabled=False)
        members = asyncio.run(get_group_members(os.getenv('STAFF_GROUP_ID')))   
        
        for member in members:

            try:
                status,errors = _repository.save_if_new(member)
                
                if not status:
                    raise GenericError({"code": "bad_request", "description": errors},400)
                    
            except Exception as e:
                handle_exception(e)

        #return Response({"members": members})
    except Exception as e:  
        handle_exception(e)

def populate_presence():

    _repository = PresenceRepository()

    try:
        
        today = datetime.today().strftime('%Y-%m-%d')
        list_presences = _repository.filteredCron(today)

        for ex_place in list_presences.get('ex_places', []):
            note = ''
            vacations = Vacations.objects.filter(user_id=ex_place['user']['id'], type=2, state_id=9, date_from__date=today)
            if vacations:
                note = 'Permessi:'
                for vacation in vacations:
                    date_from_time = (vacation.date_from + timedelta(hours=2)).strftime('%H:%M')
                    date_to_time = (vacation.date_to + timedelta(hours=2)).strftime('%H:%M')
                    note += f' {date_from_time}-{date_to_time}'
            dto = {
                "date": today,
                "type":1,
                "user":ex_place['user']['id'],
                "user_name": f"{ex_place['user']['givenName']} {ex_place['user']['surname']}",
                "notes": note,
                "from_cron": True
            }

            #if ex_place['user']['external'] == 0:
            if ex_place['user']['ci'] is not None:
                dto["check_in"] = datetime.combine(date.today(), datetime.strptime(ex_place['user']['ci'], '%H:%M:%S').time())
                dto["check_out"] = datetime.combine(date.today(), datetime.strptime(ex_place['user']['co'], "%H:%M:%S").time())
            else:
                dto["check_in"] = datetime.today().strftime('%Y-%m-%d 07:00:00')
                dto["check_out"] = datetime.today().strftime('%Y-%m-%d 16:00:00')
            
            _repository.save(dto)

        for place in list_presences.get('places', []):
            note = ''
            vacations = Vacations.objects.filter(user_id=place['user']['id'], type=2, state_id=9, date_from__date=today)
            if vacations:
                note = 'Permessi:'
                for vacation in vacations:
                    date_from_time = (vacation.date_from + timedelta(hours=2)).strftime('%H:%M')
                    date_to_time = (vacation.date_to + timedelta(hours=2)).strftime('%H:%M')
                    note += f' {date_from_time}-{date_to_time}'
            dto = {
                "date": today,
                "type":1,
                "user":place['user']['id'],
                "user_name": f"{place['user']['givenName']} {place['user']['surname']}",
                "notes": note,
                "from_cron": True
            }

            #if place['user']['external'] == 0:
            if place['user']['ci'] is not None:
                dto["check_in"] = datetime.combine(date.today(), datetime.strptime(place['user']['ci'], '%H:%M:%S').time())
                dto["check_out"] = datetime.combine(date.today(), datetime.strptime(place['user']['co'], "%H:%M:%S").time())
            else:
                dto["check_in"] = datetime.today().strftime('%Y-%m-%d 07:00:00')
                dto["check_out"] = datetime.today().strftime('%Y-%m-%d 16:00:00')
                
            _repository.save(dto)

    except Exception as e:  
        handle_exception(e)

def project_export():
    import asyncio
    from management.utils.graph import get_projects_cron
    clients = asyncio.run(get_clients_cron())
    Cliente.objects.bulk_create(clients["sp_clienti"], ignore_conflicts=True)
    users = User.objects.all()
    user_dict = {user.mail: user.id for user in users} 
    projects = asyncio.run(get_projects_cron(user_dict))

    #Commessa.objects.bulk_create(projects["sp_commessa"], ignore_conflicts=False)
    #RisorseCommessa.objects.bulk_create(projects["sp_risorse"], ignore_conflicts=False)

    with transaction.atomic():
        ids_commesse = [c.id for c in projects["sp_commessa"]]
        existing_ids = set(
            Commessa.objects.filter(id__in=ids_commesse).values_list("id", flat=True)
        )
        to_update = [c for c in projects["sp_commessa"] if c.id in existing_ids]
        to_create = [c for c in projects["sp_commessa"] if c.id not in existing_ids]
        Commessa.objects.bulk_create(projects["sp_commessa"], ignore_conflicts=True)
        if to_update:
            Commessa.objects.bulk_update(
                to_update,
                fields=["name", "resp_comm_id", "resp_prog_id", "client_id", "approval"]
            )
        if to_create:
            Commessa.objects.bulk_create(to_create, ignore_conflicts=True)
        RisorseCommessa.objects.all().delete()
        RisorseCommessa.objects.bulk_create(projects["sp_risorse"], ignore_conflicts=False)

def users_photo_export():
    import asyncio
    from management.utils.graph import get_users_photo_cron
    users = list(User.objects.all())  
    photos = asyncio.run(get_users_photo_cron(users))
    if photos:
        with transaction.atomic():
            User.objects.bulk_update(photos, ['photo'])
            print(f"Updated")
        print(f"Updated {len(photos)} users")
    # return Response(data=GenericResponseObjectSerializer(GenericResponseObject(status=True)).data)
    