from django.core.management.base import BaseCommand
import pika
from DAIManagementApp.models import Epg,Sfr_analytics
from DAIManagementApp.views import get_last_week,call_vast_api
from threading import Thread
import logging



class Command(BaseCommand):
    help = 'Listens to RabbitMQ messages'

    def handle(self, *args, **options):
        amqp_url = 'amqp://localhost?connection_attempts=10&retry_delay=2'
        url_params = pika.URLParameters(amqp_url)

        # connect to rabbitmq
        connection = pika.BlockingConnection(url_params)
        chan = connection.channel()

        # Define callback function to handle incoming messages
        def callback(ch, method, properties, body):
            print("Received message:", body)
            decoded_body = body.decode('utf-8')
            
            # GET Last Week from ads time
            last_week = get_last_week(str(decoded_body))
            last_week_day = last_week.strftime('%Y-%m-%d')
            last_week_minut = last_week.strftime('%H:%M:00')

            # Get SFR analytics volume for last week
            try:
                analytics_data = Sfr_analytics.objects.get(
                    day=last_week_day,
                    minute=last_week_minut,
                    sfr_channel_name="2M Maroc"
                )
                total_volume = round(float(analytics_data.purcent) * 4500000 / 17)
                print('Analytic SRF: ',analytics_data.minute)
            except Sfr_analytics.DoesNotExist:
                total_volume = 0
                print({"message": "SFR Not Found"})
            finally: 
                try:
                    # get epg for last week based on start and interval
                    print({"EPG":{"last_week":last_week_minut}})
                    last_week_epg = f"{last_week_day} {last_week_minut}" 
                    emission = Epg.objects.filter(start_time__lte=last_week_epg,end_time__gte=last_week_epg).first()
                    # logging.info("EPG: ",emission.emission_name)
                    # serialized_data = serializers.serialize('json', epg_data)
                    # # Convert serialized data to Python data (list of dictionaries)
                    # deserialized_data = json.loads(serialized_data)
                    # call ALMA API
                    # print("TOTAL VOLUME: ",total_volume)
                    thread = Thread(target=call_vast_api,args=("Abtal Albihar","Dessin Anime",600,19334))
                    thread.start()
                    # thread = Thread(target=call_vast_api,args=("Abtal Albihar","Dessin Anime",(emission.end_time - emission.start_time).total_seconds(),3))
                    # thread.start()
                    # print(thread.join())
                    
                    # return JsonResponse(deserialized_data)
                except Epg.DoesNotExist:
                    print({"message": "EPG Not Found"})

        # Start consuming messages
        chan.basic_consume(queue='alma', on_message_callback=callback, auto_ack=True)

        print('Waiting for messages. To exit, press CTRL+C')
        chan.start_consuming()


