from django.db import models
import ulid
from XCMS_PIM.models import WorkspaceUser
from django.db.models.constraints import UniqueConstraint
from django.forms.models import model_to_dict
from app.models.prd_sku_model import PrdSKUModel
from app.models.channel_model import ChannelModel
from XCMS_PIM.pim_cnsts import *


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 CategoryModel(models.Model):
    code = ULIDField(default=ulid.new(), primary_key=True)
    order = models.IntegerField()
    name = models.CharField(max_length=256)
    note = models.CharField(max_length=256)
    labels = models.CharField(max_length=1024)
    is_deleted = models.CharField(max_length=1)
    is_leaf = models.CharField(max_length=1)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)
    created_by = models.ForeignKey(
        WorkspaceUser,
        related_name="user_created",
        null=True,
        blank=True,
        on_delete=models.CASCADE,
        to_field="user_uid",
        db_column="created_by",
    )
    updated_by = models.ForeignKey(
        WorkspaceUser,
        related_name="user_updated",
        null=True,
        blank=True,
        on_delete=models.CASCADE,
        to_field="user_uid",
        db_column="updated_by",
    )
    parent = models.ForeignKey(
        "self", null=True, blank=True, related_name="children", on_delete=models.CASCADE, db_column="parent_code"
    )
    products = models.ManyToManyField(PrdSKUModel, related_name="categories", through="SkuCategoryModel")
    channel = models.ForeignKey(
        ChannelModel,
        related_name="categories",
        null=True,
        blank=True,
        on_delete=models.CASCADE,
        to_field="cd",
        db_column="channel_cd",
    )

    def get_highest_parent_channel(self):
        if self.parent is None:
            if self.channel is not None:
                return self.channel
            return None
        return self.parent.get_highest_parent_channel()

    def get_parent_category_tree(self):
        if self.parent is None:
            if self.channel is not None:
                return {
                    "category": model_to_dict(self, exclude=["products"]),
                    "parent": {"category": model_to_dict(self.channel)},
                }
            return {"category": model_to_dict(self, exclude=["products"]), "parent": None}
        parent_tree = self.parent.get_parent_category_tree()
        category_tree = {"category": model_to_dict(self, exclude=["products"]), "parent": parent_tree}
        return category_tree

    def get_parent_codes(self):
        if self.parent is None:
            return []
        parent_codes = self.parent.get_parent_codes()
        parent_codes.append(self.parent.code)
        return parent_codes

    def get_subtree(self, depth=2):
        if depth == 0:
            category_dict = model_to_dict(self, exclude=["products"])
            category_dict["img"] = G_ENV_PIM_CATEGORY_DATA_ADDR + self.code + G_PIM_CATEGORY_IMAGE_FILE_EXT
            return {
                "category": category_dict,
            }
        else:
            category_dict = model_to_dict(self, exclude=["products"])
            category_dict["img"] = G_ENV_PIM_CATEGORY_DATA_ADDR + self.code + G_PIM_CATEGORY_IMAGE_FILE_EXT
            category_tree = {"category": category_dict, "children": []}
            for child in self.children.filter(is_deleted="0"):
                category_tree["children"].append(child.get_subtree(depth - 1))
            return category_tree

    def get_leaf_categories(self):
        leaf_categories = []
        if self.children.count() == 0:
            leaf_categories.append(self)
        else:
            for child in self.children.filter(is_deleted="0"):
                leaf_categories += child.get_leaf_categories()
        return leaf_categories

    class Meta:
        managed = False
        db_table = "categories"
        UniqueConstraint(fields=["code"], name="category_code_unique")


class SkuCategoryModel(models.Model):
    category_cd = models.ForeignKey(
        CategoryModel,
        related_name="category_code",
        on_delete=models.DO_NOTHING,
        to_field="code",
        db_column="category_code",
    )
    sku_cd = models.ForeignKey(
        PrdSKUModel,
        related_name="category_sku_code",
        on_delete=models.DO_NOTHING,
        to_field="prd_mng_id",
        db_column="sku_code",
    )

    class Meta:
        managed = False
        db_table = "category_skus"
