from django.http import JsonResponse
from app.models.assets_model import AssetsModel
from app.models.prd_sku_model import PrdSKUModel
from app.utils.utils import get_or_none
from XCMS_PIM.models import WorkspaceUser
from XCMS_PIM.pim_cnsts import *
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework.status import HTTP_200_OK, HTTP_400_BAD_REQUEST
from rest_framework_simplejwt.authentication import JWTAuthentication
from rest_framework.permissions import IsAuthenticated
from app.utils.utils import *
import os, tempfile, shutil
import ulid


class PartiaUploadView(APIView):
    authentication_classes = (JWTAuthentication,)
    permission_classes = (IsAuthenticated,)

    def post(self, request, product_id):
        is_initial = request.POST.get("is_initial", "") == "true"
        chunk_index = request.POST.get("chunk_index", None)
        is_last = request.POST.get("is_last", "") == "true"
        file_name = request.POST.get("file_name", None)
        file_size = request.POST.get("file_size", None)
        upload_id = request.POST.get("upload_id", None)
        asset_id = request.POST.get("asset_id", None)
        asset_type = request.POST.get("asset_type", None)
        uploaded_file = request.FILES["chunk"]
        if is_initial:
            upload_id = str(ulid.new())
        upload_dir = os.path.join(tempfile.gettempdir(), upload_id)
        if not os.path.exists(upload_dir):
            os.makedirs(upload_dir)
        chunk_path = os.path.join(upload_dir, chunk_index)
        if is_last:
            return self.on_completion(request, upload_dir, file_name, file_size, product_id, asset_id, asset_type)
        else:
            with open(chunk_path, "wb+") as f:
                for chunk in uploaded_file.chunks():
                    f.write(chunk)
        return JsonResponse({"result": "success", "upload_id": upload_id}, status=HTTP_200_OK)

    def on_completion(self, request, upload_dir, file_name, file_size, product_id, asset_id, asset_type):
        file_dir = os.path.join(G_ENV_PIM_PRODUCT_DATA_STRAGE, product_id, "assets")
        if not os.path.exists(file_dir):
            os.makedirs(file_dir)
        user_id = request.user.user_uid
        user = get_or_none(WorkspaceUser, user_uid=user_id)
        ext = os.path.splitext(file_name)[1]
        if ext.startswith("."):
            ext = ext[1:]
        product_asset_def = PrdImageModel.objects.create(
            prd_mng_id=product_id,
            prdi_item_no=asset_id,
            prdi_item_type=asset_type,
            prdi_del="0",
            prdi_rsl=0,
            prdi_width=0,
            prdi_height=0,
            prdi_cl_space=0,
            prdi_format=ext,
            prdi_cls="0",
            prdi_file_name=file_name,
            prdi_caption="",
            prdi_size=file_size,
            prdi_crt_ur_cd=user.user_uid,
        )
        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, product_id)
        if not os.path.exists(lPrdImgDir):
            os.mkdir(lPrdImgDir)
        saved_path = os.path.join(lPrdImgDir, product_id) + "_" + asset_id + "_" + asset_type + "." + ext
        with open(saved_path, "wb") as f:
            for chunk_path in os.listdir(upload_dir):
                with open(os.path.join(upload_dir, chunk_path), "rb") as chunk:
                    f.write(chunk.read())
        try:
            shutil.rmtree(upload_dir)
        except OSError as e:
            print("Error: %s : %s" % (upload_dir, e.strerror))
        data = model_to_dict(product_asset_def)
        data["img"] = (
            G_ENV_PIM_PRODUCT_DATA_ADDR + product_id + "/" + product_id + "_" + asset_id + "_" + asset_type + "." + ext
        )
        return JsonResponse({"result": "success", "data": data}, status=HTTP_200_OK)
