from PIL import Image

from configs.firebase import ArrayUnion, db
from functions.Storage import downloadFile, get_file_path, saveFile


def putImage(result,path1,path2,top,left,scale,angle):
    scale = round(float(scale))
    # height = round(float(height))
    # width = round(float(width))
    # Opening the primary image (used in background)
    img1 = Image.open(path1)
    # Opening the secondary image (overlay image)
    img2 = Image.open(path2)
    img1 = img1.resize((int(452), int(566)))
    # Resizing the secondary image
    #scale down img2
    height, width = img2.size
    img2 = img2.resize((int(width*scale*0.01), int(height*scale*0.01)))
    img2 = img2.rotate(-angle)
    # Pasting img2 image on top of img1 
    # starting at coordinates (0, 0)
    img1.paste(img2,(int(left), int(top)), mask=img2.convert("RGBA"))
    # Displaying the image
    path = get_file_path(result)
    img1.save(path)
    return path

def inchToPixel(imageSizeinInch, canvasWidthinPixel, canvasWithinInch):
    return (canvasWidthinPixel / canvasWithinInch) * imageSizeinInch

def generateVariantMockImage(params:dict):
    uid, enterpriseId = params.get("currentUser").get("uid"), params.get("currentUser").get("enterpriseId")
    productId = params.get("productId")
    variantId = params.get("variantId")
    ref = db.collection("manualProducts").document(productId).collection("variations").document(variantId).get()
    doneColors = {}
    if ref.exists:
        variation = ref.to_dict()
        color = variation.get("color")
        mockGenerated = variation.get("mockGenerated")
        if mockGenerated: return
        variant = variation.get("variant", {})
        blankProductId = variant.get("blankProductId")
        images = variant.get("images", [])
        printImages = variation.get("images")
        frontImage = [i for i in images if i.get("type") == "Front"]
        if frontImage and printImages:
            frontImage = frontImage[0]
            printImage = printImages[0]
            shirtImage = downloadFile("Shirt.png",frontImage.get("url"))
            printImage = downloadFile("Print.png",printImage.get("url"))
            top = int(variant.get("top", 0))
            placements = db.collection("manualProducts").document(productId).collection("placements").document(blankProductId).get()
            blankProductSettings = db.collection("enterprises").document(enterpriseId).collection("blankProducts").document(blankProductId).get()
            if placements.exists and blankProductSettings.exists:
                blankProductSettings = blankProductSettings.to_dict()
                blankPlacementDetails = blankProductSettings.get("placementDetails", {}).get("default", {}).get("1",{}).get("objectDetails", {})
                blankTop, blankLeft  = float(blankPlacementDetails.get("top", 0)), float(blankPlacementDetails.get("left", 0))
                placements = placements.to_dict()
                placementDetails = placements.get("placementDetails", {}).get("default", {}).get("1",{}).get("objectDetails", {})
                top, left, height, width, scale = (float(placementDetails.get("top", 0))), (float(placementDetails.get("left", 0))), placementDetails.get("height", 0), placementDetails.get("width", 0), placementDetails.get("scale", 100)
                angle = float(placementDetails.get("angle", 0))
                canvasHeight = float(blankPlacementDetails.get("canvasHeight", 0))
                canvasHeightIn = (float(blankPlacementDetails.get("height", 0)))
                canvasWidthIn = (float(blankPlacementDetails.get("width", 0)))
                canvasWidth = (float(blankPlacementDetails.get("canvasWidth", 0)))
                canvasLeft = float(blankPlacementDetails.get("left", 0))
                canvasTop = float(blankPlacementDetails.get("top", 0))
                blankTop = inchToPixel(top,canvasHeight, canvasHeightIn)
                blankLeft = inchToPixel(left,canvasWidth, canvasWidthIn)
                if top and left:
                    result = putImage(f"{variantId}.png",shirtImage,printImage,
                    ((canvasTop)+(blankTop)),((canvasLeft)+(blankLeft)),scale,angle)
                    file= saveFile(
                        uid,
                        enterpriseId,f"{variantId}.png",
                        result,
                        type="products"
                    )
                    file['color'] = color
                    file['variantId'] = variantId
                    file['sku'] = variantId
                    if color not in doneColors:
                        doneColors[color] = file
                        db.collection("manualProducts").document(productId).collection("variants").document(variantId).set(dict(
                            images = ArrayUnion([file]),
                        ), merge=True)
                        db.collection("manualProducts").document(productId).set(dict(
                            images = ArrayUnion([file]),
                            colorImages=doneColors,
                        ), merge=True)
                        ref.reference.update(dict(
                            mockGenerated=True
                        ))
                    return variation
                else:
                    return "No placement details found"
            else:
                return "No placement details found"
        else:
            return "No front image found"
