from django.core.management.base import BaseCommand
import pika
from DAIManagementApp.models import VastResponseGo
from DAIManagementApp.views import get_last_week,call_vast_api
from threading import Thread
import logging
from concurrent.futures import ThreadPoolExecutor
from datetime import datetime
import requests

def vast_resume(headers,vast):

    if vast.impression_sprintserve and vast.impression_sprintserve_status == None:
        sprintserve_response = requests.get(vast.impression_sprintserve, headers=headers)
        vast.impression_sprintserve_status = sprintserve_response.text or None
        print(sprintserve_response.status_code)

    if vast.impression_double_click and vast.impression_double_click_status == None:
        double_click_response = requests.get(vast.impression_double_click, headers=headers)
        vast.impression_double_click_status = double_click_response.text 
        print(double_click_response.status_code)
        
    if vast.tracking_complete and vast.tracking_completed_status == None:
        completed_click_response = requests.get(vast.tracking_complete, headers=headers)
        vast.tracking_completed_status = completed_click_response.text 
        print(double_click_response.status_code)
    
    if vast.tracking_firstquartile and vast.tracking_firstquartile_status == None:
        first_quartile_response = requests.get(vast.tracking_firstquartile, headers=headers)
        vast.tracking_firstquartile_status = first_quartile_response.text
        print(tracking_first_quartile.status_code)

    if vast.tracking_midpoint and vast.tracking_midpoint_status == None:
        tracking_midpoint_response = requests.get(vast.tracking_midpoint, headers=headers)
        vast.tracking_midpoint_status = tracking_midpoint_response.text
        print(tracking_midpoint.status_code)
    
    if vast.tracking_thirdquartile and vast.tracking_thirdquartile_status == None:
        tracking_third_response = requests.get(vast.tracking_thirdquartile, headers=headers)
        vast.tracking_thirdquartile_status = tracking_third_response.text
        print(tracking_third_quartile.status_code)
    vast.save()



class Command(BaseCommand):
    help = 'Run the rest of requests'

    def handle(self, *args, **options):
        # get all vastresponse from 19-03-2025 to 01-04-2025
        start_date = datetime(2025, 4, 2)
        # end_date = datetime(2025, 4, 1)
        headers = {
            'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.0.0 Safari/537.36'
        }

        vast_obj = VastResponseGo.objects.filter(datetime_timestamp__date=start_date)
        with ThreadPoolExecutor(max_workers=100) as executor:
            futures = [executor.submit(vast_resume,headers=headers,vast=v) for v in vast_obj]
            response = [future.result() for future in futures]
            print(response)
        