import datetime
from sqlalchemy.dialects.postgresql import JSONB

from enum import Enum

from ..engine import db


class Domain(db.Model):
    __tablename__ = "domains"

    org_id = db.Column(db.Unicode(), primary_key=True)
    name = db.Column(db.Unicode(), primary_key=True)
    admin_id = db.Column(db.Unicode(), nullable=False)
    master = db.Column(db.Boolean(), default=False)
    display = db.Column(db.Boolean(), default=False)
    owned = db.Column(db.Boolean(), default=False)
    validated = db.Column(db.Boolean(), default=False)
    mx = db.Column(db.Boolean(), default=False)
    delegated = db.Column(db.Boolean(), default=False)
    via_webmaster = db.Column(db.Boolean(), default=False)
    created_at = db.Column(db.TIMESTAMP(timezone=True),
                           default=datetime.datetime.utcnow)
    validated_at = db.Column(db.TIMESTAMP(timezone=True))
    blocked_at = db.Column(db.TIMESTAMP(timezone=True))


class DomainAction(str, Enum):
    domain_occupied = 'domain_occupied'
    domain_deleted = 'domain_deleted'
    domain_added = 'domain_added'
    domain_alienated = 'domain_alienated'
    domain_auto_handover = 'domain_auto_handover'
    domain_deleted_with_organization = 'domain_deleted_with_organization'


class DomainHistory(db.Model):
    __tablename__ = 'domain_history'

    id = db.Column(db.BigInteger(), primary_key=True)

    org_id = db.Column(db.Unicode())
    name = db.Column(db.Unicode(), nullable=False, index=True)
    action = db.Column(db.Enum(DomainAction), nullable=False)
    author_id = db.Column(db.Unicode())
    timestamp = db.Column(db.TIMESTAMP(timezone=True),
                          default=datetime.datetime.utcnow)


class MailUserDomainStatus(str, Enum):
    pending_registrar = 'pending_registrar'
    wait_dns_entries = 'wait_dns_entries'
    registered = 'registered'
    failed = 'failed'
    cancelled_by_user = 'cancelled_by_user'
    expired = 'expired'
    probation = 'probation'
    cancelled_by_admin = 'cancelled_by_admin'


class MailUserDomain(db.Model):
    __tablename__ = 'mail_users_domains'
    id = db.Column(db.BigInteger(), primary_key=True)
    domain = db.Column(db.Unicode(), nullable=False)
    login = db.Column(db.Unicode(), nullable=False)
    uid = db.Column(db.VARCHAR(length=100), nullable=False)
    status = db.Column(db.VARCHAR(length=50), nullable=False)
    fields = db.Column(JSONB(astext_type=db.Text()), nullable=True),
    created_at = db.Column(db.TIMESTAMP(timezone=True), server_default=db.text('CURRENT_TIMESTAMP'), nullable=False)
    updated_at = db.Column(db.TIMESTAMP(timezone=True), server_default=db.text(
        'CURRENT_TIMESTAMP'), nullable=False)
    register_allowed_ts = db.Column(db.TIMESTAMP(timezone=True), nullable=True)
    service_id = db.Column(db.VARCHAR(length=50), nullable=True)
    expired_at = db.Column(db.Date(), nullable=True, index=True)
