from zeep import helpers

from configs.firebase import SERVER_TIMESTAMP, db
from functions.Suppliers.Auth import getClient, getSupplierCredentials
from functions.Suppliers.BlankProducts import getBlankProduct
from functions.Suppliers.Locations import saveLocation


def updateBlankInventory(params):
    blankProduct = getBlankProduct(params.get('id'))
    supplierId = blankProduct.get('supplierId')
    Client = getClient(supplierId, 'inventory')
    if not Client: return False
    client, version = Client
    id = blankProduct.get("blankProductId")
    creds = getSupplierCredentials(supplierId)
    InventoryResponse = helpers.serialize_object(
        client.service.getInventoryLevels(
            wsVersion=version,
            id = creds.get('username'),
            password = creds.get('password'),
            productId=id,
        ), target_cls=dict
    )
    PartInventory = InventoryResponse.get("Inventory", {})
    inventories  = []
    if PartInventory:
        try:
            PartInventory = PartInventory.get("PartInventoryArray", {})
            PartInventory = PartInventory.get('PartInventory', []) if PartInventory else []
            for inventory in PartInventory:
                totalQuantity = 0
                locations = inventory.get('InventoryLocationArray', {}).get('InventoryLocation', [])
                inventoryLocations = {}
                for location in locations:
                    quantity = int(dict(location.get('inventoryLocationQuantity', {})).get('Quantity', {}).get('value', 0))
                    inventoryLocations[location.get('inventoryLocationId')] = quantity
                    totalQuantity += quantity
                inventories.append(
                    dict( 
                        inventory = inventoryLocations,
                        totalQuantity=totalQuantity,
                        id = inventory.get('partId'),
                        updatedAt =  SERVER_TIMESTAMP
                    ),
                )
        except Exception as e:
            print("Updating Parts Inventory" , e)
            return False
    else: 
        print(InventoryResponse, client, version, creds)
        return False
    saveInventory(blankProduct.get('id'),inventories)
    return True

def saveInventory(blankProductId,inventories =[]):
    ref = db.collection('blankProducts').document(blankProductId).collection('inventoryPricings')
    for inventory in inventories:
        ref.document(inventory.get('id')).set(inventory, merge=True)
    print(f'Inventory Updated => {blankProductId}', len(inventories))
    return blankProductId