import os
from uuid import uuid4
from django.db import models
from django.urls import reverse
from django.dispatch import receiver
from django.db.models.signals import post_save
from django.core.validators import RegexValidator
from django.utils.translation import gettext_lazy as _
from django_countries.fields import CountryField
from apps.accounts.models import User

# Create your models here.

# Profile Picture
# m.lower().endswith(('.png', '.jpg', '.jpeg'))
def avatar_filename(instance, filename):
    _, file_extension = os.path.splitext(filename)
    new_filename = f'{uuid4()}{file_extension}'
    return f'profile_avatar/{new_filename}'


class AddressType(models.TextChoices):
    HOME    = 'home', 'Home'
    WORK    = 'work', 'Work'
    BILLING = 'billing', 'Billing'
    PRIMARY = 'primary', 'Primary'
    OTHER   = 'other', 'Other'

class Address(models.Model):
    street_address = models.CharField(max_length=255, blank=True, null=True)
    city = models.CharField(max_length=255, blank=True, null=True)
    state = models.CharField(max_length=255, blank=True, null=True)
    region = models.CharField(max_length=255, blank=True, null=True)
    zip_code = models.CharField(max_length=10, blank=True, null=True)
    country = CountryField(blank_label='(select country)')
    address_type = models.CharField(max_length=9, choices=AddressType.choices)

class Profile(models.Model):
    user                = models.OneToOneField(User, primary_key=True, on_delete=models.CASCADE)
    avatar              = models.ImageField(verbose_name='Profile Picture', default='profile_avatar/default.png', upload_to=avatar_filename)
    occupation          = models.CharField(max_length=255, blank=True, null=True)
    address             = models.ForeignKey(Address, on_delete=models.CASCADE, blank=True, null=True)

    phone_regex         = RegexValidator(regex=r'^\d{10,15}$', message="Phone number must be entered in the format: '+999999999'. Up to 15 digits allowed.")
    phone               = models.CharField(validators=[phone_regex], max_length=17, blank=True, null=True)
    phone_verified      = models.BooleanField(_('Is Phone Verified'), default=False)

    channel_url         = models.URLField(blank=True, null=True)
    country             = CountryField(blank_label='(select country)')
    language            = models.CharField(max_length=255, blank=True, null=True)
    time_zone           = models.CharField(max_length=255, blank=True, null=True)
    communication_phone = models.BooleanField(_('Communication With Phone'), default=False)
    communication_email = models.BooleanField(_('Communication With Email'), default=False)
    allow_changes       = models.BooleanField(_('Allow Changes'), default=False)

    def get_absolute_url(self):
        return reverse('profile', kwargs={'pk': self.user_id})

    def get_profile_update_url(self):
        return reverse('accounts:profile-update', kwargs={'pk': self.user_id})

    def get_primary_address(self):
        try:
            return self.address_set.get(address_type='primary')
        except Address.DoesNotExist:
            return None

    def get_location(self):
        if self.address != None:       
            for address in self.address_set.all():
                if address.address_type =='primary':
                    # return f"{address.state}, {address.region}, {address.country}"
                    return (address.state, address.region, address.country)
                elif address.state and address.region and address.country:
                    return (address.state, address.region, address.country)
        return (None, None, None)

    def __str__(self):
        return f'{self.user} Profile'


# profile creation signals
@receiver(post_save, sender=User)
def create_profile(sender, created,instance,**kwargs):
    if created:
        profile = Profile.objects.create(user=instance)
        profile.save()