from django.db import models
import os
import uuid
import requests
from django.contrib.auth.models import User

from django.db.models.signals import post_save
from django.dispatch import receiver

# # Create your models here.
class File(models.Model):
    id_file = models.UUIDField(primary_key=True,default=uuid.uuid4,editable=False)
    file_title =  models.CharField(max_length=500,null=True,blank=True)
    video_path=models.CharField(max_length=500,null=True,blank=True)
    language = models.CharField(max_length=10,null=True,blank=True)
    user = models.ForeignKey(User , models.DO_NOTHING,blank=True, null=True)
    duration=models.CharField(max_length=50,null=True,blank=True)
    extension=models.CharField(max_length=50,null=True)
    when_uploaded=models.DateTimeField(auto_now_add=True)
    size=models.CharField(max_length=50,null=True,blank=True)
    multi_speaker=models.BooleanField(default=False)
    file_s3_url = models.CharField(max_length=600,null=True,blank=True)

    def __str__(self):
        return str(self.video_path)


class Transcripts(models.Model):
    id_transcript = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    file_org      = models.ForeignKey(File, on_delete=models.CASCADE,null=True,blank=True)
    path_srt_fr   = models.CharField(max_length=600,blank=True,null=True)
    path_srt_es   = models.CharField(max_length=600,blank=True,null=True)
    path_srt_en   = models.CharField(max_length=600,blank=True,null=True)
    path_srt_po   = models.CharField(max_length=600,blank=True,null=True)
    # downloaded_at = models.DateTimeField(null=True,blank=True)

    def __str__(self):
        return self.file_org.file_title if self.file_org else 'Transcript {}'.format(self.id_transcript)

@receiver(post_save,sender=Transcripts)
def save_vtt(sender,instance,created,**kwargs):
    # check if objects was created and install just origin language
    if kwargs.get('created', False):
        # check video origin language
        # install video oringin language
        # stop
        # check file vtt if is available in static files
        STATIC_FILES = 'static/subtitles'
        VTT_RESPONSE = {'file': instance.file_org.file_s3_url}
        # INSTANCE_VTT = {key[9:]: str(path).replace('.srt', '.vtt') for key, path in vars(instance).items() if key.startswith('path_srt_') and path}
        INSTANCE_VTT = {
            'fr': (str(instance.path_srt_fr).replace('.srt','.vtt') if  instance.path_srt_fr else None),
            'es': (str(instance.path_srt_es).replace('.srt','.vtt') if  instance.path_srt_es else None),
            'en': (str(instance.path_srt_en).replace('.srt','.vtt') if  instance.path_srt_en else None),
            'po': (str(instance.path_srt_po).replace('.srt','.vtt') if  instance.path_srt_po else None)
        }

        for k, vtt in INSTANCE_VTT.items():
            if not vtt:
                print(f"VTT not found for {vtt} in creating")
                continue
            vtt_path = os.path.join(STATIC_FILES, f"{os.path.splitext(os.path.basename(vtt))[0]}.{k}.vtt")

            if os.path.exists(os.path.join(STATIC_FILES,vtt_path)):
                VTT_RESPONSE[k] = vtt_path
                print("VTT Path Exists: ",vtt_path)
            else:
                print(f"Downloading {vtt} In Create")
                response = requests.get(vtt)
                if response.status_code == 200:
                    with open(vtt_path, 'wb') as f:
                        f.write(response.content)

                    VTT_RESPONSE[k] = vtt_path
                else:
                    print(f"Download {vtt} Faild")


    else:
        print("Updating Transcript object ...")
        # check file vtt if is available in static files
        STATIC_FILES = 'static/subtitles'
        VTT_RESPONSE = {'file': instance.file_org.file_s3_url}
        # INSTANCE_VTT = {key[9:]: str(path).replace('.srt', '.vtt') for key, path in vars(instance).items() if key.startswith('path_srt_') and path}
        INSTANCE_VTT = {
            'fr': (str(instance.path_srt_fr).replace('.srt','.vtt') if  instance.path_srt_fr else None),
            'es': (str(instance.path_srt_es).replace('.srt','.vtt') if  instance.path_srt_es else None),
            'en': (str(instance.path_srt_en).replace('.srt','.vtt') if  instance.path_srt_en else None),
            'po': (str(instance.path_srt_po).replace('.srt','.vtt') if  instance.path_srt_po else None)
        }

        for k, vtt in INSTANCE_VTT.items():
            if not vtt:
                print(f"VTT not found for {vtt}")
                continue
            vtt_path = os.path.join(STATIC_FILES, f"{os.path.splitext(os.path.basename(vtt))[0]}.{k}.vtt")

            if os.path.exists(os.path.join(STATIC_FILES,vtt_path)):
                VTT_RESPONSE[k] = vtt_path
                print("VTT Path Exists: ",vtt_path)
            else:
                print(f"Downloading {vtt} In Update")
                response = requests.get(vtt)
                if response.status_code == 200:
                    with open(vtt_path, 'wb') as f:
                        f.write(response.content)

                    VTT_RESPONSE[k] = vtt_path
                else:
                    print(f"Download {vtt} Faild")


# STATIC_FILES = 'static/subtitles'
        # VTT_RESPONSE = {'file': instance.file_org.file_s3_url}
        # INSTANCE_VTT = None
        # vtt = None
        # if "en" in instance.file_org.language:
        #     INSTANCE_VTT = {'en': (str(instance.path_srt_es).replace('.srt','.vtt') if  instance.path_srt_es else None),}
        #     vtt="en"
        # if "fr" in instance.file_org.language:
        #     INSTANCE_VTT={'fr': (str(instance.path_srt_fr).replace('.srt','.vtt') if  instance.path_srt_fr else None),}
        #     vtt="fr"
        # if "es" in instance.file_org.language:
        #     INSTANCE_VTT={'es': (str(instance.path_srt_fr).replace('.srt','.vtt') if  instance.path_srt_fr else None),}
        #     vtt = "es"
        # if "po" in instance.file_org.language:
        #     INSTANCE_VTT={'po': (str(instance.path_srt_fr).replace('.srt','.vtt') if  instance.path_srt_fr else None),}
        #     vtt = "po"
        # # install origin language

        # if not INSTANCE_VTT[vtt]:
        #     print(f"VTT not found for {vtt}")
        # vtt_path = os.path.join(STATIC_FILES, f"{os.path.splitext(os.path.basename(INSTANCE_VTT[vtt]))[0]}.{k}.vtt")

        # if os.path.exists(os.path.join(STATIC_FILES,vtt_path)):
        #     VTT_RESPONSE[k] = vtt_path
        #     print("VTT Path Exists: ",vtt_path)
        # else:
        #     print(f"Downloading {INSTANCE_VTT[vtt]}")
        #     response = requests.get(INSTANCE_VTT[vtt])
        #     if response.status_code == 200:
        #         with open(vtt_path, 'wb') as f:
        #             f.write(response.content)
        #         VTT_RESPONSE[k] = vtt_path
    # check if object was updated