import traceback
from datetime import datetime

import requests

from functions.Bigcartel.Auth import getAuth
from V2.functions.Address.main import Address
from V2.functions.Images.main import Image
from V2.functions.Orders.main import Order
from V2.functions.Orders.OrderItem import OrderItem
from V2.functions.Shops.main import Shop, getShopsByPlatformId
from V2.Params import Params


def updateAllOrders(params:Params):
    shops = getShopsByPlatformId(platformId="8", credentials= True)
    return str([updateShopOrders(shop) for shop in shops])

def updateShopOrders(shop:Shop):
    try:
        shopId = shop.id
        updates:list[str] = []
        res = getBigcartelOrders(shop)
        orders = res.get('data') 
        included = res.get('included')
        print("updating orders", shopId, len(orders))
        for order in orders:
            attributes = order.get('attributes')
            itemIds =[item.get("id") for item in  order.get('relationships').get('items').get('data')]
            items = [item for item in included if item.get('type') == "order_line_items" and item.get("id") in itemIds]
            convertedItems =  [] 
            for item in items:
                try:
                    platformProductId = item.get("relationships",{}).get('product',{}).get("data",{}).get("id", "None")
                    variantId = item.get("relationships",{}).get('product_option',{}).get("data",{}).get("id", "None")
                except:
                    platformProductId = "None"
                    variantId = "None"
                convertedItems.append(
                        OrderItem(
                                uid=shop.uid,
                                enterpriseId=shop.enterpriseId,
                                platformId=shop.platformId,
                                shopId=shopId,
                                platformOrderId=order.get('id'),
                                createdAt=datetime.fromisoformat(attributes.get('created_at').replace("Z","")),
                                updatedAt=datetime.fromisoformat(attributes.get('updated_at').replace("Z","")),
                                name=item.get("attributes").get('product_name'),
                                platformOrderItemId=item.get('id'),
                                quantity=item.get("attributes").get('quantity'),
                                platformProductId=platformProductId,
                                productId=shop.platformId+shop.id+platformProductId,
                                price=item.get("attributes").get('price'),
                                image=Image(url=item.get("attributes").get('image_url')),
                                images=[
                                    dict(url=item.get("attributes").get('image_url'))
                                ],
                                subtotal=item.get("attributes").get('total'),
                                total=item.get("attributes").get('total'),
                                variantId=variantId,
                                discount=0,
                                tax=0    )
                                )
            convertedOrder =  Order(
                uid=shop.uid,
                enterpriseId=shop.enterpriseId,
                platformId=shop.platformId,
                shopId=shopId,
                platformOrderId=order.get('id'),
                createdAt=datetime.fromisoformat(attributes.get('created_at').replace("Z","")),
                updatedAt=datetime.fromisoformat(attributes.get('updated_at').replace("Z","")),
                grandTotal=attributes.get('total'),
                shipped=attributes.get('shipping_status') == "shipped",
                shippingAddress=Address(
                    name=f"{attributes.get('customer_first_name')} {attributes.get('customer_last_name')}",
                    address1=attributes.get('shipping_address_1'),
                    address2=attributes.get('shipping_address_2'),
                    city=attributes.get('shipping_city'),
                    state=attributes.get('shipping_state'),
                    zip=attributes.get('shipping_zip'),
                    country=attributes.get('shipping_country'),
                    phone=attributes.get('shipping_phone'),
                    email=attributes.get('shipping_email'),
                    countryCode=attributes.get('shipping_country_code'),
                ),
                cancelled=attributes.get('payment_status') == "cancelled",
                draft=False,
                totalDiscount=attributes.get("discount_total"),
                totalPrice=attributes.get('subtotal'),
                totalTax=attributes.get("tax_total"),
                shippingCost=attributes.get("shipping_total")
            )
            updates.append(convertedOrder.save(orderItems=convertedItems, rewrite=True))
        return updates
    except Exception as e:
        print(traceback.format_exc())
        return str(e)

def getBigcartelOrders(shop:Shop):
    """Get all orders from Bigcartel"""
    # Get all orders from Bigcartel
    url = 'https://api.bigcartel.com/v1/accounts/{}/orders.json'.format(shop.platformShopId)
    params = dict(sort="updated_at")
    response = requests.get(url, headers=getAuth(shop.accessToken), params=params)
    orders = response.json()
    return orders