from datetime import datetime

from sp_api.api import Orders

from configs.firebase import db
from functions.Amazon.Auth import createCredentials
from functions.Amazon.Products import updateSingleProduct
from functions.LastUpdated import ordersLastUpdated, saveOrdersLastUpdated
from functions.Orders import (convertOrder, convertOrderItem,
                              convertShippingAddress, saveOrder)
from functions.Response import saveError
from functions.Shops import getShops


def updateAllOrders(params={}):
    shops = getShops(platformId="7", credentials= True)
    res = [updateShopOrders(shop) for shop in shops]
    return str(res)


def updateShopOrders(shop:dict):
    if shop:
        uid = shop.get('uid')
        shopId  = shop.get('id')
        platformId = shop.get('platformId')
        refreshToken = shop.get('refreshToken')
        enterpriseId = shop.get('enterpriseId')
        credentials = createCredentials(refreshToken)
        lastUpdate = ordersLastUpdated(shopId)
        # 7 days ago from now
        updated_at_min = int(datetime.now().timestamp()) - 86400*7
        updated_at_min= datetime.fromtimestamp(updated_at_min).strftime("%Y-%m-%dT%H:%M:%SZ")
        try:
            orders = getOrders(credentials, updated_at_min)
            if not orders: return
            updates = []
            products = []
            convertedOrders = []
            for order in orders:
                orderId = order.get('AmazonOrderId')
                orderNumber = order.get('SellerOrderId')
                shipping_address = order.get("ShippingAddress")
                createdAt, updatedAt = datetime.fromisoformat(order.get('PurchaseDate').replace("Z", "")), datetime.fromisoformat(order.get('LastUpdateDate').replace("Z", ""))
                convertededOrder = convertOrder(
                        uid=uid,
                        platformId=platformId,
                        shopId=shopId,
                        enterpriseId=enterpriseId,
                        shippingAddress=convertShippingAddress(
                            name = shipping_address.get('Name'), 
                            address1= shipping_address.get('AddressLine1'),
                            address2= shipping_address.get('AddressLine2'),
                            city= shipping_address.get('City'),
                            state= shipping_address.get('StateOrRegion'),
                            zip= shipping_address.get('PostalCode'),
                            country= shipping_address.get('CountryCode'),
                            phone= order.get('Phone'),
                        ),
                        cancelled = bool(order.get("OrderStatus") == "Canceled"),
                        shipped= order.get('OrderStatus') == "Shipped",
                        createdAt= createdAt,
                        updatedAt= updatedAt,
                        platformOrderId=orderId,
                        currencyCode=order.get('OrderTotal').get('CurrencyCode'),
                        grandTotal= order.get('OrderTotal').get('Amount'),
                        totalPrice= order.get('OrderTotal').get('Amount'),
                        orderNumber=orderNumber,
                        MarketplaceId = order.get('MarketplaceId'),
                    )
                orderItems = getOrderItems(credentials, orderId)
                for item in orderItems: 
                    products.append(item.get("ASIN"))
                convertedOrderItems = [convertOrderItem(
                            uid = uid,
                            platformId = platformId,
                            enterpriseId=enterpriseId,
                            platformOrderItemId= item.get('OrderItemId'),
                            platformOrderId = orderId,
                            shopId=shopId,
                            cancelled=bool(order.get("OrderStatus") == "Canceled"),
                            createdAt= createdAt,
                            updatedAt= updatedAt,
                            name= item.get('Title'),
                            platformProductId= item.get('ASIN'),
                            price= item.get('ItemPrice', {}).get('Amount'),
                            quantity= item.get('QuantityOrdered'),
                            shipped= order.get('OrderStatus') == "Shipped",
                            variantId= item.get('ASIN'),
                            tax=item.get("ItemTax").get("Amount"),
                            discount = item.get("PromotionDiscount").get("Amount"),
                            sku=item.get("SellerSKU")
                            # variantProperties=[convertProperty(key, value) for key,value in item.items() if type(value) == str and value!="Title"] + [convertProperty(key, value) for key,value in buyersInfo.items() if type(value) == str],
                        ) for item in orderItems 
                        ]
                convertedOrders.append((convertededOrder, convertedOrderItems))
            print(set(products))
            variantIds = {}
            for product in set(products):
               variantIds[product] = updateSingleProduct(dict(
                shopId = shopId,
                shop =shop,
                platformProductId = product
               ))
            for order, orderItems in convertedOrders:
                for item in orderItems: item['variantId'] = variantIds.get(item.get("productId"))
                updates.append(saveOrder(order, orderItems, True))
                print(order.get("platformOrderId"))
            nowTimestamp = int(datetime.now().timestamp())
            saveOrdersLastUpdated(shopId = shopId, count= len(updates),timestamp=nowTimestamp)
            return f"Orders updated => {len(updates)}" 
        except Exception as e:
            print(e)
            saveError(uid, "Shopify/Orders/updateShopOrders", str(e),data =  dict(
                shopId=shopId,
                lastUpdate=lastUpdate
            ))
    return "No Updates"

import json


def getOrders(credentials, createdAfter):
    from sp_api.base import Marketplaces
    MarketplaceIds=['ATVPDKIKX0DER']
    res = Orders(credentials=credentials, marketplace=Marketplaces.US).get_orders(CreatedAfter=createdAfter,OrderStatuses=['Shipped','Canceled','Unshipped'],MarketplaceIds=MarketplaceIds)
    if not res.errors:
        with open("Orders.json", "w") as file:
            file.write(json.dumps(res.payload.get("Orders")))
        return res.payload.get("Orders", [])
    else:
        print(res.errors)
    return []

def getOrder(credentials, orderId = "113-1528849-6233869"):
    print(orderId)
    from sp_api.base import Marketplaces
    MarketplaceIds=['ATVPDKIKX0DER']
    res = Orders(credentials=credentials, marketplace=Marketplaces.US).get_order(orderId, MarketplaceIds=MarketplaceIds)
    if not res.errors:
        return res.payload
    else:
        print(res.errors)
    return None

def getOrderItems(credentials, orderId):
    from sp_api.base import Marketplaces
    res = Orders(credentials=credentials, marketplace=Marketplaces.US).get_order_items(orderId)
    if not res.errors:
        return res.payload.get("OrderItems", [])
    else: print(res.errors)
    return []

def getOrderItemsBuyerInfo(credentials, orderId):
    from sp_api.base import Marketplaces
    res = Orders(credentials=credentials, marketplace=Marketplaces.US).get_order_items_buyer_info(orderId)
    if not res.errors:
        return {item.get("OrderItemId"):item.get("BuyerCustomizedInfo", {}) for item in res.payload.get("OrderItems", [])}
    print(res.errors)
    return {}

# def getOrderAddress(credentials, orderId):
#     from sp_api.base import Marketplaces
#     res = Orders(credentials=credentials, marketplace=Marketplaces.US).get_order_address(orderId)
#     if not res.errors:
#         print( res.payload)
#         return res.payload
#     print(res.errors)
#     return {}


def receiveAmazonOrders(params):
    orders = params.get('orders')
    currentUser = params.get("currentUser")
    batch = db.batch()
    try: db.collection("AmazonOrdersTemp").document(str(datetime.now().timestamp())).set(params)
    except Exception as e:
        print(e)
        return dict(success=False)
    for order in orders:
        order['currentUser'] = currentUser
        batch.set(db.document(f"amazonorders/{datetime.now().timestamp()}"), order)
    batch.commit()
    return dict(success=True)

def receiveBuyerInfo(params):
    try: 
        db.collection("BuyerInfoTemp").document(str(datetime.now().timestamp())).set(dict(params))
        return dict(success=True)
    except Exception as e: 
        print(e)
    return dict(success=False)
    