from django.db import models
from django.db.models.signals import post_save
from django.dispatch import receiver
from ckeditor.fields import RichTextField

from apps.accounts.models import User

# Create your models here.

class Extention(models.Model):
    value = models.CharField(max_length=6)
    # plan = models.ForeignKey(Plan, on_delete=models.PROTECT)

    def __str__(self):
        return self.value


class PlanType(models.TextChoices):
    Yearly      = 'Yearly'
    Monthly     = 'Monthly'
    Weekly       = 'Weekly'

# class paymentSourceInfo(models.Model):
#
#     paymentSource_id   = models.CharField(max_length=200, unique=True)
#     paymentSource_name = models.CharField(max_length=200, unique=True)

#     def __str__(self):
#         return self.paymentSource_name


class Plan(models.Model):
    # plan_id             = models.UUIDField(primary_key=False, default=uuid.uuid4, editable=False)
    plan_id               = models.CharField(max_length=200, unique=True)
    plan_type             = models.CharField(max_length=30)
    plan_name             = models.CharField(max_length=30)  # free | basic | premium
    plan_duration         = models.CharField(max_length=25, choices=PlanType.choices, default=PlanType.Monthly) # monthly | yearly | weekly
    describe              = RichTextField(config_name='awesome_ckeditor')
    price                 = models.FloatField(default=0)
    paymentSource         = models.CharField(max_length=200)  # Paypal/Stripe
    # paymentSource         = models.ForeignKey(paymentSourceInfo, on_delete=models.PROTECT)  # Paypal/Stripe

    duration_days         = models.IntegerField(default=5)

    videos_per_day        = models.IntegerField(default=1)
    time_per_video        = models.TimeField(auto_now=False, auto_now_add=False)
    upload_youtube_perm   = models.BooleanField(default=False)
    download_youtube_perm = models.BooleanField(default=False)
    file_size             = models.FloatField(default=1)
    parts_limits          = models.FloatField(default=1)
    valid_extentions      = models.ManyToManyField(Extention)

    created               = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return f"Plan :{self.plan_name} {self.plan_duration} with paypal ID: {self.plan_name} created at: {self.created}"

    def get_valid_extentions(self):
        return [v.value for v in self.valid_extentions.all()]

class Subscription(models.Model):
    created_at = models.DateTimeField(auto_now_add=True)
    modified_at = models.DateTimeField(auto_now=True)
    plan = models.ForeignKey(Plan, on_delete=models.PROTECT)
    user = models.OneToOneField(User, on_delete=models.PROTECT)
    start_time = models.DateTimeField(auto_now_add=True)
    ends_time = models.DateField(auto_now_add=False, blank=True, null=True)
    is_active = models.BooleanField(default=False)
    paid_status = models.BooleanField(default=False)  # payment gateway

    def __str__(self):
        return f"User : {self.user} Make a Subscription With {self.plan}"

    def get_plan_type(self):
        return str(self.plan.plan_type)

class Payment(models.Model):
    created_at = models.DateTimeField(auto_now_add=True)
    modified_at = models.DateTimeField(auto_now=True)
    transactionID = models.CharField(max_length=100, blank=True, null=True)
    conversationID = models.CharField(max_length=100, blank=True, null=True)
    reference_no = models.CharField(max_length=150, blank=True, null=True)  # payment gateway
    subscription = models.ForeignKey(Subscription, on_delete=models.CASCADE)
    sub_id = models.CharField(max_length=255)
    is_active = models.BooleanField(default=False)

    class Meta:
        ordering = ('created_at',)
    def __str__(self):
        return str(f"Payment Trans ID: {self.transactionID}")

class PendingSubs(models.Model):
    plan_id = models.CharField(max_length=255,null=True,blank=True)
    payment = models.ForeignKey(Payment,on_delete=models.CASCADE)
    revise_failed_reason = models.CharField(max_length=255)

    def __str__(self):
        return f"Payment {self.payment.sub_id} pending"

@receiver(post_save, sender=Subscription)
def set_endtime(sender, created,instance,**kwargs):
    if created:
        from datetime import datetime, timedelta
        instance.ends_time = instance.start_time+timedelta(days=int(instance.plan.duration_days))
        instance.save()
    

