from datetime import datetime
import json
from functions.Suppliers.Auth import getClient, getSupplierCredentials
from configs.firebase import db
from functions.Response import API_Error
from zeep import helpers
def sendPO(params):
    purchaseOrderId = params.get("purchaseOrderId")
    purchaseOrder = db.collection("purchaseOrders").document(purchaseOrderId).get()
    if not purchaseOrder.exists: raise API_Error("PO Not found.", 404)
    email = params.get("currentUser").get("email")
    supplierId = purchaseOrder.get("supplierId")
    enterpriseId = purchaseOrder.get("enterpriseId")
    supplierCredentials = getSupplierCredentials(supplierId, enterpriseId)
    if not supplierCredentials: raise API_Error("Supplier Credentials not found.", 404)
    purchaseOrder = purchaseOrder.to_dict()
    total = purchaseOrder.get("total")
    address = db.collection("addresses").document(purchaseOrder.get("addressId")).get()
    if not address.exists: raise API_Error("Address not found.", 404)
    address = address.to_dict()
    blankProducts = [b.to_dict() for b in db.collection("purchaseOrders").document(purchaseOrderId).collection("blankProducts").get()]
    lineItems = {}
    quantities = {}
    totals = {}
    for blankProduct in blankProducts:
        part = dict(
            partGroup=1,
            locationLinkId = blankProduct.get("locationId"),
            Quantity = dict(
                value = blankProduct.get("quantity"),
                uom = "PK"
            ),
            partId = blankProduct.get("blankVariantId"),
            customerSupplied=False,
        )
        quantity = blankProduct.get("quantity")+ quantities.get(blankProduct.get("blankProductId"), 0)
        quantities[blankProduct.get("blankProductId")] = quantity
        currentItems = lineItems.get(blankProduct.get('blankProductId'), []) 
        currentItems.append(part)
        totals[blankProduct.get("blankProductId")] = totals.get(blankProduct.get("blankProductId"), 0) + (blankProduct.get("price")* blankProduct.get("quantity"))
        lineItems[blankProduct.get('blankProductId')]=currentItems
    print(quantities)
    po = {
            "currency": "USD",
            "LineItemArray": {
            "LineItem": [{
                "PartArray": {
                    "Part": part
                },
                "allowPartialShipments": True,
                "lineNumber": 1,
                "lineType": "New",
                "description": "",
                # "extendedPrice": 10,
                "Quantity": {
                    "value": quantities.get(blankProductId),
                    "uom": "PK"
                },
                "ToleranceDetails": {
                "tolerance": "AllowOverrun"
                },
                "productId": str(blankProductId).replace(supplierId, ""),
                "lineItemTotal": totals.get(blankProductId),
            } for blankProductId, part in lineItems.items()] 
            },
            "orderDate": datetime.today().isoformat(),
            "orderNumber": purchaseOrderId,
            "orderType": "Blank",
            # "orderVersion": 1,
            "rush": True,
            "ShipmentArray": {
            "Shipment": {
                "ShipTo": {
                "shipmentId": 1,
                "ContactDetails": {
                    "attentionTo": address.get("name"),
                    "address1": address.get("address1"),
                    "city": address.get("city"),
                    "region": address.get("state"),
                    "postalCode": address.get("zip"),
                    "country": "US",
                    "email": email,
                    "phone": address.get("phone"),
                    "comments": "",
                  },
                    "customerPickup":False,
                },
                "packingListRequired": True,
                "blindShip": False,
                "allowConsolidation": True,
                "FreightDetails": {
                "carrier": "UPS",
                "service": "GROUND"
                }
            }
            },
            "termsAndConditions": "",
            "totalAmount": total
        }
    print(json.dumps(po, indent=4))
    client, version = getClient(supplierId, "purchaseOrder")
    res = client.service.sendPO(
        wsVersion = version,
        id = supplierCredentials.get("username"),
        password = supplierCredentials.get("password"),
        PO=po
    )
    res = helpers.serialize_object(res, target_cls=dict)
    return res