from datetime import datetime

from configs.firebase import SERVER_TIMESTAMP, db
from functions.Products import convertProduct, convertProperty, convertVariant
from functions.products.ManualProduct import saveManualProduct
from functions.Response import API_Error


def manualProductWithPlacementDetails(params):
    currentUser = params.get("currentUser")
    uid, enterpriseId = currentUser.get('uid'), currentUser.get('enterpriseId')
    product = params.get("product")
    productDetails = product.get("productDetails")
    selectedBlankNicknames = params.get('selectedBlankNicknames')
    placementDetails = params.get('placementDetails')
    variations = product.get('variations')
    decorationType = product.get('decorationType')
    printType = product.get('printType', '1')
    variants = []
    blankProductIds = []
    doneSKUs= []
    prices = []
    price =  productDetails.get('price', 10)
    pImages = []
    defaultPlacement, defaultVariation = None, None
    primaryImages = []
    canvasImages = []
    variantType = "color"
    blank = list(placementDetails.keys())[0]
    # for blank in placementDetails:
    variantType = placementDetails[blank].get("variantType", "color")
    previewImages = placementDetails[blank]['previewImages']
    thisCanvasImages = placementDetails[blank].get("canvasImages")
    if variantType == "color": 
        # thisCanvasImages = thisCanvasImages.get("default")
        # if not thisCanvasImages: 
        thisCanvasImages = dict(placementDetails[blank].get("canvasImages", {}))
        if printType != "0" and thisCanvasImages:
            for color, printImages in thisCanvasImages.items():
                canvasImages.extend(
                    [
                        {
                            'id': i.get("id"),
                            'url': i.get("url"),
                            'placement': placement,
                            'blankProductId': blank,
                            "imageConfigs": i.get("imageConfigs"),
                            "productType": i.get("productType"),
                            "smallerImageUrl": i.get("smallerImageUrl"),
                            "color":color,
                            "name": i.get("name", i.get("id"))
                        } for placement, i in printImages.items()
                    ]
                )
            # canvasImages.extend([{
            #         'id': i.get("id"),
            #         'url': i.get("url"),
            #         'placement': k,
            #         'blankProductId': blank,
            #         "imageConfigs": i.get("imageConfigs"),
            #         "productType": i.get("productType"),
            #         "smallerImageUrl": i.get("smallerImageUrl"),
            #         "color":k
            #     } for k,i in thisCanvasImages.items() if k != "default"])
    else:
        for size, printImages in thisCanvasImages.items():
            # print(size, printImages)
            for p, i in printImages.items():
                canvasImages.append(
                    dict(
                        id = i.get("id"),
                        url = i.get("url"),
                        placement = p,
                        blankProductId=blank,
                        imageConfigs=i.get("imageConfigs"),
                        size=size,
                        productType = i.get("productType"),
                        smallerImageUrl = i.get("smallerImageUrl"),
                        name=i.get("name",i.get("id"))
                    )
                )
        # canvasImages.extend([{'id': i.get("id"), 'url': i.get("url"), 'placement': k, 'blankProductId': blank, "imageConfigs": i.get("imageConfigs")} for k,i in thisCanvasImages.items() if k != "default"])
    if not (defaultPlacement or defaultVariation):
        defaultPreview = placementDetails[blank].get("defaultPreview")
        if defaultPreview:
            defaultPlacement = defaultPreview.get("placement")
            defaultVariation = defaultPreview.get("variation")
        # defaultVariation, defaultPlacement = defaultPreview.get('variation'), defaultPreview.get("placement")
    pImages.extend([{
            'blankProductId': blank,
            "color": p,
            'images': [
                {
                    'placement':k,
                    'blankProductId':blank,
                    'color':p,
                    'id': i.get('id'),
                    'url':i.get('url')
                } for k,i in previewImages[p].items()]
            }
        for p in previewImages])
    pImages = {p.get('color'): p.get('images') for p in pImages}
    if defaultPlacement and defaultVariation:
        try: primaryImages = pImages.get(defaultVariation, [])
        except: pass
    else: primaryImages = list(pImages.values())[0] if pImages else []
    imageIds = [i.get('id') for i in canvasImages]
    for variation in variations:
        try:
            price = float(variation.get('price', 10))
        except Exception as e:
            raise API_Error("Price should be valid number. Remove any currency symbols.")
        sku= variation.get('sku', str(datetime.now().timestamp()))
        if not sku:
            raise API_Error("SKU is required.")
        if "/" in sku:
            raise API_Error("SKU should not contain '/'.")
        if sku in doneSKUs:
            raise API_Error("SKU must be unique for each variant.")
        doneSKUs.append(sku)
        decorationType = variation.get("decorationType")
        # variantImages = []
        # variantImages.extend([i.get("images", []) for i in pImages if i.get('color') == variation.get('color')][0])
        # convertedVariant['images'] = variantImages
        variation['id'] = sku
        blankProductId = variation.get("blankId")
        mapping = variation.get('variant')
        if not blankProductId:  blankProductId = mapping.get("blankProductId")
        blankProductIds.append(mapping.get("blankProductId"))
        svgOutline = mapping.get('svgOutline')
        images = [i for i in canvasImages if i.get("blankProductId") == blankProductId and i.get(variantType) == variation.get(variantType)]
        if not images: images = [i for i in canvasImages if i.get("blankProductId") == blankProductId and i.get(variantType) == "default"]
        convertedVariant = convertVariant(
                id=sku,
                price=price,
                properties=[convertProperty("Color", variation.get('color')), convertProperty("Size", variation.get("size"))],
                sku=sku,
                images=pImages.get(variation.get('color'))
            )
        variantMapping = dict(
            id= sku, 
            blankProductId=blankProductId,
            blankVariantId = mapping.get('id'),
            images = images,
            sku = sku,
            gtin = mapping.get("gtin"),
            svgOutline = svgOutline,
            decorationType=decorationType,
        )
        variants.append((convertedVariant, variantMapping, variation))
        prices.append(price)
    product = convertProduct(
            uid = uid,
            platformId="0",
            shopId="0"+uid,
            enterpriseId=enterpriseId,
            platformProductId=str(int(datetime.now().timestamp())),
            price = price if price else min(prices),
            name= productDetails.get('title', productDetails.get('name')),
            description= productDetails.get('description'),
            createdAt=SERVER_TIMESTAMP,
            updatedAt=SERVER_TIMESTAMP,
            tags=productDetails.get("tags", []),
            images = primaryImages,
        )
    # print(product, productDetails)
    productMapping = dict(
        blankProductIds = list(set(blankProductIds)),
        enterpriseId = enterpriseId,
        ignored=False,
        imageIds = list(set(imageIds)),
        printOnDemand=productDetails.get('printOnDemand', True),
        decorationType=decorationType,
        uid=uid,
        updatedAt=SERVER_TIMESTAMP
    )
    product['skus'] = doneSKUs
    product['productDetails'] = productDetails
    product['productMapping'] = productMapping
    product['selectedBlankNicknames'] = selectedBlankNicknames
    product['printType'] = printType
    id = saveManualProduct(product, variants)
    product['id'] = id
    for color in pImages:
        db.collection("manualProducts").document(id).collection('colorImages').document(str(color).replace("/", "-")).set(dict(images=pImages[color]))
    for blankProductId in placementDetails:
        placementDetail = placementDetails[blankProductId]
        db.collection("manualProducts").document(id).collection("placements").document(blankProductId).set(placementDetail)
    return product