from app.entities import models
from app.applicationlayer import paginators
from datetime import datetime
from rest_framework.response import Response
from rest_framework import status, views

from django.db.models import Q
import requests
from django.conf import settings
from datetime import timedelta
from app.helper.email_service import sender
from app.applicationlayer.utils import main_threading
from rest_framework.permissions import AllowAny

CR_FRONT_LINK = settings.CR_FRONT_LINK

class OverdueTriggerAPIView(views.APIView):

    permission_classes = (AllowAny,)

    def get(self, request):
        date_now = datetime.now()
        today_mail = models.OverdueTrigger.objects.filter(
            Q(overdue_date=date_now.strftime('%Y-%m-%d 00:00:00.000')) &
            Q(is_sent=False)
        )
        
        list_of_emails = []
        for data in today_mail:
            
            if data.is_sent == False and (data.form_code.status == 'Pending' or
               data.form_code.status == 'Approved' or
               data.form_code.status == 'Rejected'):
                
                cr_link = f'{CR_FRONT_LINK}/{data.form_code}'
                
                requestor_name = data.form_code.requested_by_user.name
                target_date = data.form_code.requested_to_target_date.strftime('%B %d, %Y')
                cr_number = data.form_code.requested_to_template_id
                cr_name = data.form_code.requested_to_template_name
                company_requestedto = data.form_code.requested_to_company.name
                department_requestedto = data.form_code.requested_to_department.name
                priority_level = data.form_code.requested_to_priority
                form_status = data.form_code.status
                url = cr_link
                requestor_recipient = data.form_code.requested_by_user.email
                admin = 'Test'
                
                args_requestor = [requestor_name, target_date,
                    cr_number, cr_name, company_requestedto,
                    department_requestedto, priority_level, form_status, url,
                    requestor_recipient, admin]
                
                main_threading(args_requestor, sender.routing_table_overdue)

                list_of_emails.append(data.form_code.form_code)

        today_mail.update(is_sent=True)

        return Response(
            {"list of emails": list_of_emails},
            status=status.HTTP_200_OK
        )


