from django.db import models
from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin
from .managers import UserManager


class BasicUser(AbstractBaseUser, PermissionsMixin):
    """
    Model defining User accounts.
    """

    username = models.CharField(max_length=15, unique=True, blank=False)
    email = models.EmailField(max_length=254, unique=True, blank=False)
    first_name = models.CharField(max_length=50, blank=False)
    last_name = models.CharField(max_length=50, blank=False)
    gender = models.CharField(max_length=50, blank=True, choices=[
        ("M", "Male"),
        ("F", "Female"),
        ("NB", "Non-Binary"),
        ("O", "Other"),
        ("NA", "Prefer Not To Answer")
    ])
    birthdate = models.DateField(blank=True, null=True)
    address_1 = models.CharField(max_length=100, blank=True)
    address_2 = models.CharField(max_length=200, blank=True)
    city = models.CharField(max_length=50, blank=True)
    state = models.CharField(max_length=2, blank=True)
    zip_code = models.CharField(max_length=15, blank=True)
    is_active = models.BooleanField(default=True)
    is_admin = models.BooleanField(default=False)

    objects = UserManager()

    USERNAME_FIELD = 'username'
    EMAIL_FIELD = 'email'
    REQUIRED_FIELDS = [
        "email",
        "first_name",
        "last_name"
    ]

    class Meta:
        verbose_name = "User"
        verbose_name_plural = "Users"

    def __str__(self):
        return self.first_name + " " + self.last_name

    def has_perm(self, perm, obj=None):
        return True

    def has_module_perms(self, app_label):
        return True

    @property
    def is_staff(self):
        return self.is_admin


def get_file_path(instance, filename):
    ext = filename.split('.')[-1]
    filename = "%s.%s" % (instance.user.id, ext)
    return "images/profile/"+filename


class ProfileImage(models.Model):
    """
    Model defining Profile Images for User accounts.
    """
    user = models.OneToOneField(
        BasicUser, on_delete=models.CASCADE, primary_key=True, related_name="profile_image")
    image = models.ImageField(
        upload_to=get_file_path,
        default="images/profile/default.png"
    )
    created_at = models.DateTimeField(auto_now_add=True, editable=False)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        verbose_name = "Profile Picture"
        verbose_name_plural = "Profile Pictures"
