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
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
from django.db.models import Q

import io, os
import json
import ulid
import base64
import cv2
import numpy as np
from PIL import Image

from XCMS_PIM.pim_cnsts import *

from app.models.img_item_def_model import ImgItemDefModel
from app.models.prd_image_model import PrdImageModel
from app.format_image_module.convert_file2image_formats import convert_file2img
from app.format_image_module.SwinSR_Model.swin2sr_net import ImageResolutionUpScaler
from app.utils.utils import *
from app.utils.consts import *


class ProductImageDef(APIView):
    authentication_classes = (JWTAuthentication,)
    permission_classes = (IsAuthenticated,)

    def get(self, request):

        lResult = "success"

        lPrdImgDef = ImgItemDefModel.objects.filter(iid_del="0").order_by("iid_order")

        lResponseData = {
            "result": lResult,
            "data": list(
                lPrdImgDef.values(no=F("iid_item_no"), type=F("iid_type"), lbl=F("iid_label"), ext=F("iid_ext"))
            ),
        }

        return JsonResponse(lResponseData, safe=False, status=HTTP_200_OK)


class ProductIdsFromCodes(APIView):
    authentication_classes = (JWTAuthentication,)
    permission_classes = (IsAuthenticated,)

    def post(self, request):
        data = json.loads(request.body)
        product_codes = data["product_codes"]
        product_ids = {
            product.prd_cd: product.prd_mng_id for product in PrdSKUModel.objects.filter(prd_cd__in=product_codes)
        }

        return JsonResponse({"result": "success", "data": product_ids}, safe=False, status=HTTP_200_OK)


class ProductImageDefRegister(APIView):
    authentication_classes = (JWTAuthentication,)
    permission_classes = (IsAuthenticated,)

    def post(self, request):
        data = json.loads(request.body)
        product_asset = ImgItemDefModel.objects.filter(
            iid_del="0", iid_item_no=data["no"], iid_type=data["type"]
        ).first()

        if product_asset is not None:
            response = {"result": "failure", "message": "既に登録されています。"}
            return JsonResponse(response, safe=False, status=HTTP_200_OK)
        else:
            ImgItemDefModel.objects.create(
                iid_item_no=data["no"],
                iid_type=data["type"],
                iid_del="0",
                iid_order=data["order"],
                iid_label=data["lbl"],
                iid_cls="0",
                iid_nn="0",
                iid_ext=data["ext"],
                iid_use_appl="",
            )
        response = {"result": "success"}
        return JsonResponse(response, safe=False, status=HTTP_200_OK)


class ProductImageDefUpdate(APIView):
    authentication_classes = (JWTAuthentication,)
    permission_classes = (IsAuthenticated,)

    def post(self, request):
        data = json.loads(request.body)
        product_asset = ImgItemDefModel.objects.filter(
            iid_del="0", iid_item_no=data["no"], iid_type=data["type"]
        ).first()

        if product_asset is not None:
            product_asset.iid_order = data["order"]
            product_asset.iid_label = data["lbl"]
            product_asset.iid_ext = data["ext"]
            product_asset.save()
        else:
            response = {"result": "failure", "message": "登録されていません。"}
            return JsonResponse(response, safe=False, status=HTTP_200_OK)
        response = {"result": "success"}
        return JsonResponse(response, safe=False, status=HTTP_200_OK)


class ProductImageDefDelete(APIView):
    authentication_classes = (JWTAuthentication,)
    permission_classes = (IsAuthenticated,)

    def post(self, request):
        data = json.loads(request.body)
        product_asset = ImgItemDefModel.objects.filter(
            iid_del="0", iid_item_no=data["no"], iid_type=data["type"]
        ).first()

        if product_asset is not None:
            product_asset.iid_del = "1"
            product_asset.save()
        else:
            response = {"result": "failure", "message": "登録されていません。"}
            return JsonResponse(response, safe=False, status=HTTP_200_OK)
        response = {"result": "success"}
        return JsonResponse(response, safe=False, status=HTTP_200_OK)


class ProductImageMng(APIView):
    authentication_classes = (JWTAuthentication,)
    permission_classes = (IsAuthenticated,)

    def get(self, request, prd_mng_id):

        lResult = "success"

        lPrdImgDatas = PrdImageModel.objects.filter(prdi_del="0", prd_mng_id=prd_mng_id)

        lPrdImgDatas = list(
            lPrdImgDatas.values(
                no=F("prdi_item_no"),
                type=F("prdi_item_type"),
                rsl=F("prdi_rsl"),
                w=F("prdi_width"),
                h=F("prdi_height"),
                clspc=F("prdi_cl_space"),
                fmt=F("prdi_format"),
                name=F("prdi_file_name"),
                cap=F("prdi_caption"),
                size=F("prdi_size"),
            )
        )
        for lPrdImgData in lPrdImgDatas:
            if lPrdImgData["type"] == ASSET_TYPES.IMAGE:
                lPrdImgData["img"] = (
                    G_ENV_PIM_PRODUCT_DATA_ADDR
                    + prd_mng_id
                    + "/"
                    + prd_mng_id
                    + "_"
                    + lPrdImgData["no"]
                    + G_PIM_PRODUCT_IMAGE_FILE_EXT_THUMB
                )
            else:
                lPrdImgData["img"] = (
                    G_ENV_PIM_PRODUCT_DATA_ADDR
                    + prd_mng_id
                    + "/"
                    + prd_mng_id
                    + "_"
                    + lPrdImgData["no"]
                    + "_"
                    + lPrdImgData["type"]
                    + "."
                    + lPrdImgData["fmt"]
                )

        lResponseData = {"result": lResult, "data": lPrdImgDatas}

        return JsonResponse(lResponseData, safe=False, status=HTTP_200_OK)

    def post(self, request, prd_mng_id):

        lResult = "failure"
        data = json.loads(request.body)
        image_b64data = base64.b64decode(data["img"])
        image_data = Image.open(io.BytesIO(image_b64data))
        if not os.path.exists(G_ENV_PIM_PRODUCT_DATA_STRAGE):
            os.mkdir(G_ENV_PIM_PRODUCT_DATA_STRAGE)
        lPrdImgDir = os.path.join(G_ENV_PIM_PRODUCT_DATA_STRAGE, prd_mng_id)
        if not os.path.exists(lPrdImgDir):
            os.mkdir(lPrdImgDir)
        lPrdImgData = PrdImageModel.objects.filter(
            prd_mng_id=prd_mng_id, prdi_item_no=data["no"], prdi_del="0", prdi_item_type=ASSET_TYPES.IMAGE
        ).first()
        if lPrdImgData is not None:
            image_path = (
                os.path.join(lPrdImgDir, prd_mng_id)
                + "_"
                + get_file_name_without_ext(lPrdImgData.prdi_file_name)
                + "_"
                + lPrdImgData.prdi_item_no
                + G_PIM_PRODUCT_IMAGE_FILE_EXT
            )
            image_thumb_path = (
                os.path.join(lPrdImgDir, prd_mng_id)
                + "_"
                + lPrdImgData.prdi_item_no
                + G_PIM_PRODUCT_IMAGE_FILE_EXT_THUMB
            )
            if os.path.exists(image_path):
                os.remove(image_path)
            if os.path.exists(image_thumb_path):
                os.remove(image_thumb_path)
            lPrdImgData.prdi_rsl = int(image_data.info["dpi"][0]) if IsExistKey(image_data.info, "dpi") else 0
            lPrdImgData.prdi_width = image_data.width
            lPrdImgData.prdi_height = image_data.height
            lPrdImgData.prdi_cl_space = image_data.mode
            lPrdImgData.prdi_format = image_data.format
            lPrdImgData.prdi_cls = "0"
            lPrdImgData.prdi_file_name = data["name"]
            lPrdImgData.prdi_caption = ""
            lPrdImgData.save()
        else:
            lPrdImgData = PrdImageModel.objects.create(
                prd_mng_id=prd_mng_id,
                prdi_item_no=data["no"],
                prdi_item_type=ASSET_TYPES.IMAGE,
                prdi_del="0",
                prdi_rsl=int(image_data.info["dpi"][0]) if IsExistKey(image_data.info, "dpi") else 0,
                prdi_width=image_data.width,
                prdi_height=image_data.height,
                prdi_cl_space=image_data.mode,
                prdi_format=image_data.format,
                prdi_cls="0",
                prdi_file_name=data["name"],
                prdi_caption="",
            )
        image_data.convert("RGB").save(
            os.path.join(lPrdImgDir, prd_mng_id)
            + "_"
            + get_file_name_without_ext(data["name"])
            + "_"
            + data["no"]
            + G_PIM_PRODUCT_IMAGE_FILE_EXT
        )

        # Create Thumbnail
        lThmubWidth = G_PIM_PRD_IMAGE_THUMB_WIDTH
        lThmubHeight = G_PIM_PRD_IMAGE_THUMB_HEIGHT
        lWidthOrg, lHeightOrg = image_data.size
        if lWidthOrg * lThmubHeight > lHeightOrg * lThmubWidth:
            lThmubWidth = lWidthOrg * lThmubHeight / lHeightOrg
        elif lWidthOrg * lThmubHeight < lHeightOrg * lThmubWidth:
            lThmubHeight = lHeightOrg * lThmubWidth / lWidthOrg

        image_data.thumbnail((lThmubWidth, lThmubHeight), Image.LANCZOS)
        image_data.convert("RGB").save(
            os.path.join(lPrdImgDir, prd_mng_id) + "_" + data["no"] + G_PIM_PRODUCT_IMAGE_FILE_EXT_THUMB,
            format="JPEG",
        )

        lResult = "success"

        lResponseData = {"result": lResult}

        return JsonResponse(lResponseData, safe=False, status=HTTP_200_OK)


class ProductImageUpdateFormat(APIView):
    authentication_classes = (JWTAuthentication,)
    permission_classes = (IsAuthenticated,)

    def post(self, request, prd_mng_id):
        # Get the image file from the request

        lResult = "failure"
        data = json.loads(request.body)

        lPrdImgDir = os.path.join(G_ENV_PIM_PRODUCT_DATA_STRAGE, prd_mng_id)
        if not os.path.exists(lPrdImgDir):
            return

        imgFormat = str(data["outputFormat"])
        resize = (int(data["imgWidth"]), int(data["imgHeight"]))
        image_path = os.path.join(lPrdImgDir, prd_mng_id) + "_" + data["imageId"] + G_PIM_PRODUCT_IMAGE_FILE_EXT
        imgExtension = "jpg"

        # Save the resized image to the server
        outputImgPath = G_ENV_PIM_PRODUCT_SAVE_DATA_ADDR
        outputFileName = prd_mng_id + "_" + data["imageId"]  # prd_mng_id

        convert_file2img(image_path, imgExtension, outputImgPath, outputFileName, imgFormat, resize)
        lResult = "success"
        # Return success response
        return JsonResponse({"result": lResult}, status=HTTP_200_OK)


class ProductImageUpdateResolution(APIView):
    authentication_classes = (JWTAuthentication,)
    permission_classes = (IsAuthenticated,)

    def post(self, request, prd_mng_id):
        # Get the image file from the request
        import time

        lResult = "failure"
        data = json.loads(request.body)
        lPrdImgDir = os.path.join(G_ENV_PIM_PRODUCT_DATA_STRAGE, prd_mng_id)
        if not os.path.exists(lPrdImgDir):
            return
        image_path = os.path.join(lPrdImgDir, prd_mng_id) + "_" + data["imageId"] + G_PIM_PRODUCT_IMAGE_FILE_EXT
        # Save the high resolution image to the server
        outputImgPath = G_ENV_PIM_PRODUCT_SAVE_SUPER_RESOLUTION_DATA_ADDR
        outputFileName = prd_mng_id + data["imageId"]

        # loading model for image super resolution
        model_pth = "app/format_image_module/SwinSR_Model/models/Swin2SR_RealworldSR_X4_64_BSRGAN_PSNR.pth"
        upScaler = ImageResolutionUpScaler(model_pth)  # Model path
        new_res = upScaler.imageSuperResolution(image_path)  # image path

        cv2.imwrite(outputImgPath + outputFileName + ".png", new_res)

        lResult = "success"
        # Return success response
        return JsonResponse({"result": lResult}, status=HTTP_200_OK)


class ProductImageDel(APIView):
    authentication_classes = (JWTAuthentication,)
    permission_classes = (IsAuthenticated,)

    def get(self, request):
        return Response(status=HTTP_500_INTERNAL_SERVER_ERROR)

    def post(self, request, prd_mng_id):

        lResult = "failure"
        data = json.loads(request.body)

        lPrdImg = get_object_or_404(PrdImageModel, prd_mng_id=prd_mng_id, prdi_item_no=data["no"], prdi_del="0")
        img_no = lPrdImg.prdi_item_no
        name = get_file_name_without_ext(lPrdImg.prdi_file_name)
        lPrdImgDir = os.path.join(G_ENV_PIM_PRODUCT_DATA_STRAGE, prd_mng_id)
        lPrdImgFile = os.path.join(lPrdImgDir, prd_mng_id) + "_" + name + "_" + img_no + G_PIM_PRODUCT_IMAGE_FILE_EXT
        if os.path.exists(lPrdImgFile):
            os.remove(lPrdImgFile)

        lPrdImgThumbFile = os.path.join(lPrdImgDir, prd_mng_id) + "_" + img_no + G_PIM_PRODUCT_IMAGE_FILE_EXT_THUMB
        if os.path.exists(lPrdImgThumbFile):
            os.remove(lPrdImgThumbFile)

        lPrdImg.delete()
        lResult = "success"

        lResponseData = {"result": lResult}

        return JsonResponse(lResponseData, safe=False, status=HTTP_200_OK)


def IsExistKey(pParentDict, pKey):

    isExistKey = False
    try:
        pParentDict[pKey]
        isExistKey = True
    except KeyError:
        pass

    return isExistKey
