import crypt
from hmac import compare_digest as compare_hash
from django.contrib.auth.models import AbstractBaseUser
from django.contrib.auth.models import PermissionsMixin

from django.db import models


class Alias(models.Model):
    id = models.AutoField(primary_key=True)
    source_username = models.CharField(max_length=64, blank=True)
    source_domain = models.CharField(max_length=255)
    destination_username = models.CharField(max_length=64)
    destination_domain = models.CharField(max_length=255)
    enabled = models.BooleanField(default=True)

    class Meta:
        managed = False
        db_table = 'aliases'
        unique_together = (('source_domain', 'source_username'),)

    def __str__(self):
        return self.source_username + '@' + self.source_domain


class Domain(models.Model):
    domain = models.CharField(max_length=255)

    class Meta:
        managed = False
        db_table = 'domains'

    def __str__(self):
        return self.domain


class Mailbox(models.Model):
    id = models.AutoField(primary_key=True)
    username = models.CharField(max_length=64)
    domain = models.CharField(max_length=255)
    password = models.CharField(max_length=255)
    quota = models.IntegerField(blank=True, null=True)
    enabled = models.BooleanField(default=True)
    sendonly = models.BooleanField(default=False)

    class Meta:
        managed = False
        db_table = 'mailboxes'
        unique_together = (('domain', 'username'),)

    def set_password(self, password):
        self.password = '{SHA512-CRYPT}' + crypt.crypt(password)

    def check_password(self, password):
        hash = crypt.crypt(password, self.password.lstrip('{SHA512-CRYPT}'))
        return compare_hash(hash, self.password.lstrip('{SHA512-CRYPT}'))

    def is_active(self):
        return bool(self.enabled)

    def __str__(self):
        return self.username + '@' + self.domain


class TLSPolicy(models.Model):
    domain = models.CharField(max_length=255)
    policy = models.TextField()
    params = models.CharField(max_length=255, blank=True, null=True)

    class Meta:
        managed = False
        db_table = 'tlspolicies'

    def __str__(self):
        return self.domain


class DomainOwner(models.Model):
    domain = models.ForeignKey(Domain, on_delete=models.CASCADE, related_name='admin')
    admin = models.CharField(max_length=200)
    source = models.CharField(max_length=8, choices=[('system', 'system'), ('ldap', 'ldap'), ('mail', 'mail')],
                              default=0)

    class Meta:
        unique_together = (('domain', 'admin', 'source'),)

    def __str__(self):
        return self.admin
