from django.shortcuts import render, redirect, get_object_or_404
from rest_framework import viewsets

from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework.status import (
    HTTP_200_OK,
    HTTP_401_UNAUTHORIZED,
    HTTP_204_NO_CONTENT,
    HTTP_400_BAD_REQUEST,
    HTTP_422_UNPROCESSABLE_ENTITY,
)
from rest_framework_simplejwt.authentication import JWTAuthentication
from rest_framework.permissions import IsAuthenticated

from rest_framework import permissions
from django.http.response import JsonResponse

from django.views.decorators.csrf import csrf_exempt
from django.db.models import F

import os
import json
import ulid
import base64
import cv2
import numpy as np

from XCMS_PIM.pim_cnsts import *
from app.utils.utils import *
from app.models.attributes_model import AttributesModel
from app.models.product_classification_model import ProductClassificationAttributeModel
from app.models.prd_sku_attrib_model import PrdSKUAttribModel
from XCMS_PIM.models import WorkspaceUser
from django.forms.models import model_to_dict
from django.db.models import Q


class AttributeListView(APIView):
    authentication_classes = (JWTAuthentication,)
    permission_classes = (IsAuthenticated,)

    def get(self, request, type):
        filter = Q(is_deleted="0") & ~Q(cd="PRD_CD")
        attributes = AttributesModel.objects.filter(filter).order_by("order")
        lResult = "success"
        data = []
        if type == "basic":
            data = list(attributes.only("cd", "is_fixed", "is_common", "name", "unit").values())
        else:
            data = list(attributes.values())
        lResponseData = {
            "result": lResult,
            "data": data,
        }
        return JsonResponse(lResponseData, safe=False, status=HTTP_200_OK)


class AttributeManage(APIView):
    authentication_classes = (JWTAuthentication,)
    permission_classes = (IsAuthenticated,)

    def get(self, request, cd):
        attribute = get_or_none(AttributesModel, cd=cd)
        if attribute is None:
            return Response(status=HTTP_204_NO_CONTENT)
        serialized_attribute = model_to_dict(attribute)
        return JsonResponse(serialized_attribute, safe=False, status=HTTP_200_OK)


class RegisterAttribute(APIView):
    authentication_classes = (JWTAuthentication,)
    permission_classes = (IsAuthenticated,)

    def get(self, request):
        pass

    def post(self, request):
        attributes = json.loads(request.body)
        user_id = request.user.user_uid
        attributes_to_register = []
        for attribute in attributes:
            if "name" not in attribute:
                continue
            name = attribute["name"]
            with_unit = getOrDefault(attribute, "with_unit")
            common = getOrDefault(attribute, "is_common")
            label = getOrDefault(attribute, "label")
            control = getOrDefault(attribute, "control_type")
            not_null = getOrDefault(attribute, "not_null")
            max_length = getOrDefault(attribute, "max_length")
            select_list = getOrDefault(attribute, "select_list")
            default_value = getOrDefault(attribute, "default_value")
            unit = getOrDefault(attribute, "unit")
            user = get_or_none(WorkspaceUser, user_uid=user_id)
            created_by = user
            updated_by = user
            attribute = AttributesModel(
                cd=ulid.new(),
                name=name,
                is_deleted="0",
                is_fixed="0",
                is_common=common,
                alternative_name=label,
                control_type=control,
                not_null=not_null,
                max_length=max_length,
                select_list=select_list,
                default_value=default_value,
                unit=unit,
                created_by=created_by,
                updated_by=updated_by,
                is_with_unit=with_unit,
            )
            attributes_to_register.append(attribute)
        AttributesModel.objects.bulk_create(attributes_to_register)
        return JsonResponse(getSuccessResponseData(), safe=False, status=HTTP_200_OK)


class UpdateAttribute(APIView):
    authentication_classes = (JWTAuthentication,)
    permission_classes = (IsAuthenticated,)

    def post(self, request, cd):
        data = json.loads(request.body)
        user_id = request.user.user_uid
        attribute = get_or_none(AttributesModel, cd=cd)
        if attribute is None:
            return Response(status=HTTP_422_UNPROCESSABLE_ENTITY)
        name = getOrDefault(data, "name", attribute.name)
        with_unit = getOrDefault(data, "with_unit", attribute.is_with_unit)
        common = getOrDefault(data, "is_common", attribute.is_common)
        alternative_name = getOrDefault(data, "alternative_name", attribute.alternative_name)
        control = getOrDefault(data, "control_type", attribute.control_type)
        not_null = getOrDefault(data, "not_null", attribute.not_null)
        is_private = getOrDefault(data, "is_private", attribute.is_private)
        is_with_unit = getOrDefault(data, "is_with_unit", attribute.is_with_unit)
        max_length = getOrDefault(data, "max_length", attribute.max_length)
        select_list = getOrDefault(data, "select_list", attribute.select_list)
        default_value = getOrDefault(data, "default_value", attribute.default_value)
        unit = getOrDefault(data, "unit", attribute.unit)
        user = get_or_none(WorkspaceUser, user_uid=user_id)
        attribute.name = name
        attribute.is_with_unit = with_unit
        attribute.is_common = common
        attribute.alternative_name = alternative_name
        attribute.control_type = control
        attribute.not_null = not_null
        attribute.max_length = max_length
        attribute.select_list = select_list
        attribute.default_value = default_value
        attribute.is_private = is_private
        attribute.is_with_unit = is_with_unit
        attribute.unit = unit
        attribute.updated_by = user
        attribute.save()
        return JsonResponse(getSuccessResponseData(), safe=False, status=HTTP_200_OK)


class DeleteAttribute(APIView):
    authentication_classes = (JWTAuthentication,)
    permission_classes = (IsAuthenticated,)

    def post(self, request, cd):
        attribute = get_or_none(AttributesModel, cd=cd)
        if attribute is None:
            return Response(status=HTTP_422_UNPROCESSABLE_ENTITY)
        is_binded_with_product_classification = ProductClassificationAttributeModel.objects.filter(
            attribute_id=cd
        ).exists()
        is_binded_with_product = PrdSKUAttribModel.objects.filter(prda_item_no=cd).exists()
        if is_binded_with_product_classification or is_binded_with_product:
            return JsonResponse({"result": "failure", "reason": "attribute-binded"}, safe=False, status=HTTP_200_OK)
        attribute.is_deleted = "1"
        attribute.save()
        return JsonResponse(getSuccessResponseData(), safe=False, status=HTTP_200_OK)
