from django.contrib.auth.models import AbstractUser
from django.db import models

class ClientPermission(models.Model):
    codename = models.CharField(max_length=100, default='')
    name = models.CharField(max_length=255, default='')

    class Meta:
        managed = True
        default_permissions = ()
        permissions = (
            ('can_book_container', 'Can book container'),
            ('can_view_bookings', 'Can view bookings'),
            ('can_manage_company_users', 'Can manage company users'),
        )
    def __str__(self):
        return self.name

class DepotUser(AbstractUser):

    phone_number = models.CharField(max_length=15, blank=True, null=True)
    email = models.EmailField(unique=True, blank=False, null=False)
    company = models.ForeignKey(
        'common.CompanyModel',
        on_delete=models.CASCADE,
        related_name='user_lines',
        blank=True,
        null=True
    )
    line = models.ForeignKey(
        'common.LinesModel',
        on_delete=models.CASCADE,
        related_name='user_lines',
        blank=True,
        null=True
    )

    company_permissions = models.ManyToManyField('ClientPermission')
    new_field1 = models.BooleanField(default=False)
    is_company_admin = models.BooleanField(default=False)

    def has_company_perm(self, perm_codename):
        if self.is_superuser:
            return True
        return self.company_permissions.filter(
            codename=perm_codename,
            is_client_permission=self.company
        ).exists()