from django.contrib.auth.models import (AbstractBaseUser, BaseUserManager,
                                        PermissionsMixin)
from django.core.mail import send_mail
from django.db import models
from store.models import Product
from django.utils.translation import gettext_lazy as _
#from django_countries.fields import CountryField
from django.core.mail import send_mail
from django.utils import timezone
from django.db.models.signals import pre_save
from django.dispatch import receiver

class CustomAccountManager(BaseUserManager):

    def create_superuser(self, email, user_name, password, **other_fields):

        other_fields.setdefault('is_staff', True)
        other_fields.setdefault('is_superuser', True)
        other_fields.setdefault('is_active', True)

        if other_fields.get('is_staff') is not True:
            raise ValueError(
                'Superuser must be assigned to is_staff=True.')
        if other_fields.get('is_superuser') is not True:
            raise ValueError(
                'Superuser must be assigned to is_superuser=True.')

        return self.create_user(email, user_name, password, **other_fields)

    def create_user(self, email, user_name, password, **other_fields):

        if not email:
            raise ValueError(_('You must provide an email address'))

        email = self.normalize_email(email)
        user = self.model(email=email, user_name=user_name, **other_fields)
        user.set_password(password)
        user.is_active = False  # Set the user as inactive until email confirmation
        user.save()
        # Send registration confirmation email
        subject = 'Confirm your registration'
        message = 'Please click the link below to confirm your registration: [confirmation_link]'
        user.email_user(subject, message)  # Call the email_user method defined in the UserBase model
        return user



class UserBase(AbstractBaseUser, PermissionsMixin):

    email = models.EmailField(_('email address'), unique=True)
    user_name = models.CharField(max_length=150, unique=True)
    first_name = models.CharField(max_length=150, blank=True)
    phone_number = models.CharField(max_length=15, blank=True)
    subscriptions = models.ManyToManyField('Subscription', blank=True, related_name='users')
    about = models.TextField(_(
        'about'), max_length=500, blank=True)
    
    # User Status
    scheduler = models.ManyToManyField('SchedulerStatus', blank=True, related_name='users')
    is_scheduler_active = models.BooleanField(default=False)  # Новое поле
    is_active = models.BooleanField(default=False)
    is_staff = models.BooleanField(default=False)
    created = models.DateTimeField(auto_now_add=True)
    updated = models.DateTimeField(auto_now=True)

    objects = CustomAccountManager()

    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = ['user_name']

    def email_user(self, subject, message):
        send_mail(
            subject,
            message,
            'info@kim-math.ru',
            [self.email],
            fail_silently=False,
        )
    
    def __str__(self):
        return self.user_name
    
    def has_active_subscription(self):
         return Subscription.objects.filter(user=self, is_active=True).exists()
    
    def has_activate_scheduler(self):
        return SchedulerStatus.objects.filter(user=self, is_running=True).exists()
        
    class Meta:
        verbose_name = "Accounts"
        verbose_name_plural = "Accounts"

        
class Subscription(models.Model):
    user = models.ForeignKey('UserBase', on_delete=models.CASCADE, related_name='user_subscriptions')
    product = models.ForeignKey(Product, on_delete=models.CASCADE, to_field='part_number', blank=True, null=True)
    start_date = models.DateField()
    end_date = models.DateField()
    is_active = models.BooleanField(default=True)
    
    def is_subscription_active(self):
        return self.is_active and self.end_date >= timezone.now().date()

    def save(self, *args, **kwargs):
        # При каждом сохранении записи, проверяем и обновляем is_active
        self.is_active = self.is_subscription_active()
        super(Subscription, self).save(*args, **kwargs)
        
    def __str__(self):
        return f'Subscription for {self.user.user_name}'
        
@receiver(pre_save, sender=Subscription)
def update_subscription_status(sender, instance, **kwargs):
    if instance.start_date <= timezone.now().date() <= instance.end_date:
        instance.is_active = True
    else:
        instance.is_active = False
        
class SchedulerStatus(models.Model):
    user = models.ForeignKey('UserBase', on_delete=models.CASCADE, related_name='scheduler_status', null='True')
    is_running = models.BooleanField(default=True)