from django.db import models
from django.db.models.constraints import UniqueConstraint
import ulid
from XCMS_PIM.models import WorkspaceUser


class ULIDField(models.CharField):
    def __init__(self, *args, **kwargs):
        kwargs["max_length"] = 26
        super(ULIDField, self).__init__(*args, **kwargs)

    def db_type(self, connection):
        return "char(26)"


class AttributesModel(models.Model):
    cd = ULIDField(default=ulid.new(), primary_key=True)
    name = models.CharField(max_length=256)
    is_deleted = models.CharField(max_length=1)
    is_fixed = models.CharField(max_length=1)
    is_common = models.CharField(max_length=1)
    is_with_unit = models.CharField(max_length=1)
    is_private = models.CharField(max_length=1)
    order = models.IntegerField()
    alternative_name = models.CharField(max_length=256)
    control_type = models.CharField(max_length=1)
    not_null = models.CharField(max_length=1)
    max_length = models.IntegerField()
    select_list = models.CharField(max_length=1024)
    default_value = models.CharField(max_length=256)
    unit = models.CharField(max_length=100)
    option1 = models.CharField(max_length=45)
    option2 = models.CharField(max_length=45)
    option3 = models.CharField(max_length=45)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)
    created_by = models.ForeignKey(
        WorkspaceUser,
        related_name="created_attributes",
        on_delete=models.DO_NOTHING,
        to_field="user_uid",
        db_column="created_by",
    )
    updated_by = models.ForeignKey(
        WorkspaceUser,
        related_name="updated_attributes",
        on_delete=models.DO_NOTHING,
        to_field="user_uid",
        db_column="updated_by",
    )

    class Meta:
        managed = False
        db_table = "attributes_t"
        UniqueConstraint(fields=["cd"], name="attrib_unique")
        UniqueConstraint(fields=["name"], name="attrib_unique_name")
