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 CancelTriggerAPIView(views.APIView):

    permission_classes = (AllowAny,)

    def get(self, request):
        date_now = datetime.now()
        today_mail = models.CancelTrigger.objects.filter(
            Q(auto_cancel_date=date_now.strftime('%Y-%m-%d 00:00:00.000'))
        )
        
        list_of_emails = []
        for data in today_mail:
            
            if data.is_sent == False and data.form_code.status == 'Pending' and data.frm_approver.is_action == True:
                
                cr_link = f'{CR_FRONT_LINK}/{data.form_code}'
                
                requestor_name = data.form_code.requested_by_user.name
                auto_cancel_date = data.auto_cancel_date.strftime('%B %d, %Y')
                date_submitted_last_approver = data.date_submitted_last_approver.strftime('%B %d, %Y')
                approver_pending_action = data.frm_approver.user.name
                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, auto_cancel_date, 
                    date_submitted_last_approver, approver_pending_action,
                    cr_number, cr_name, company_requestedto,
                    department_requestedto, priority_level, form_status, url,
                    requestor_recipient, admin]
                
                main_threading(args_requestor, sender.routing_table_cancelled)

                cancel = models.ChangeRequestFormHeader.objects.filter(
                    form_code=data.form_code
                ).update(status='Cancelled')
                
                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
        )

