from datetime import datetime
from time import sleep

from configs.firebase import db
from functions.Invoices import getCurrency
from functions.Shipments.Main import submitShipmentToPlatform
from V2.functions.Orders.main import Order
from V2.functions.Shipments.main import Shipment
from V2.functions.Shops.main import Shop
from V2.middlewares.auth import API_Error
from V2.Params import Params


def manualShipment(params:Params):
    user = params.currentUser
    enterpriseId = user.enterpriseId
    orderId = params.id
    trackingCode = params.args.get('trackingCode')
    trackingUrl = params.args.get("trackingUrl")
    shipmentCost = params.args.get("shipmentCost", 0)
    carrierName = params.args.get("carrierName", 0)
    carrierService = params.args.get("carrierService", 0)
    imageUrl = params.args.get("imageUrl")
    order = Order.get(orderId)
    if order.shipped: raise API_Error("Order already shipped.")
    currency = getCurrency(user.enterpriseId)
    if not order: raise API_Error("Order not found.", 404)
    if enterpriseId == "60D7GFDlMFFd6IsK1e58" and not (trackingCode or trackingUrl or carrierName): raise API_Error("Tracking number and carrier are required.")
    shipment = Shipment(
        carrierName=carrierName,
        carrierService=carrierService,
        cost=shipmentCost,
        createdAt=datetime.now(),
        updatedAt=datetime.now(),
        currency=currency,
        enterpriseId=user.enterpriseId,
        uid=user.uid,
        id=f"{order.id}-{int(datetime.now().timestamp())}",
        image=imageUrl,
        orderId=order.id,
        pdf=None,
        platformId="0",
        platformName="Manual",
        platformOrderId=order.platformOrderId,
        platformShipmentId=None,
        routedOrderIds=order.routedOrderIds,
        trackingCode=trackingCode,
        trackingUrl=trackingUrl,
        userUid=order.uid,
    )
    shipment.save(routedOrderIds=order.routedOrderIds)
    if trackingCode and carrierName:
        submitShipmentToPlatform(order.platformId, order.shopId, order.platformOrderId, trackingCode, carrierName,carrierService, order=order)
        # shop = Shop.get(order.shopId)
        # if order.platformId == "1":
        #     from V2.functions.Etsy.Orders import submitShipment
        #     submitted = submitShipment(shop, order.platformOrderId, trackingCode=trackingCode, carrierName=carrierName)
    sleep(1)
    order.markAsShipped(shipment=shipment)
    return shipment.to_dict()

