from datetime import datetime

import pytz
import requests

from configs.firebase import db
from V2.functions.Orders.main import Order, OrderItem
from V2.functions.Printify.Auth import printifyTime
from V2.functions.Printify.Orders import findPrintifyOrder, getPrintifyOrder
from V2.Params import Params

api_keys = {
    "FJQsdKRMyURH8efVSFzk": "efc480de-a199-49ac-8246-6f455289c15d",
    "60D7GFDlMFFd6IsK1e58": "cbb99e50-3b75-472d-8bec-1c4896693932"
}

urls = {
    "FJQsdKRMyURH8efVSFzk": "https://pphub-merch.printify.com",
    "60D7GFDlMFFd6IsK1e58": "https://pphub.printify.com"
}
# sandbox_api_key = "efc480de-a199-49ac-8246-6f455289c15d"
# api_key = "cbb99e50-3b75-472d-8bec-1c4896693932"

def sendPrintifyEventEndpoint(params:Params):
    orderId = params.args.get("orderId")
    event = params.args.get("event")
    enterpriseId = params.currentUser.enterpriseId
    platformOrderId = params.args.get("platformOrderId")
    alreadyEvent = findEvent(orderId, event.get("affected_item"), event.get("type"))
    if not alreadyEvent:
        return savePrintifyEvent(
            orderId, platformOrderId,api_key=api_keys[enterpriseId],url=urls[enterpriseId], **event
            )
    return alreadyEvent


def savePrintifyEvent(orderId:str, printfyOrderId:str,api_key:str,url:str, **event):
    event = dict(
        occurred_at = event.get("time"),
        **event 
    )
    data = dict(
        event=event,
        orderId=orderId,
        printfyOrderId=printfyOrderId,
        createdAt=datetime.now()
    )
    _, ref = db.collection("printifyEvents").add(data)
    barcodes = []
    for barcode in event.get("barcodes", []):
        barcodes.append(dict(
            barcode=barcode
        ))
    event['barcodes'] = barcodes
    event['event_id'] = ref.id
    # items = tuple(event.items())
    # for field, value in items:
    #     if not value: del event[field]
    # remove none values from event
    # remove time field from event
    # del event['time']
    event = {key:value for key, value in event.items() if value is not None}
    del event['time']
    response = sendPrintifyEvent(printfyOrderId,api_key,url, [event])
    ref.update({ "id": ref.id, "event": event, "response":{
        "text": response.text,
        "status_code": response.status_code
    }})
    return data

def findEvent(orderId, affected_item, type):
    query = db.collection("printifyEvents").where("orderId", "==", orderId).where("event.affected_item", "==", affected_item).where("event.type", "==", type).limit(1).get()
    if len(query)>0:return query[0].to_dict()
    return None

def sendPrintifyEvent(printifyOrderId:str,api_key:str,url:str, events:list[dict]):
    url = f"{url}/api/v1/orders/{printifyOrderId}/events.json"
    headers = {"X-API-KEY": api_key, "Content-Type": "application/json"}
    response = requests.post(url, headers=headers, json=events)
    return response

def printifyQc(params: Params):
    printifyOrderId = params.args.get("printifyOrderId")
    itemId = params.args.get("itemId")
    verification_passed  = params.args.get("verification_passed")
    order_id = params.args.get("order_id")
    barcode = params.args.get("barcode")
    if not barcode: barcode = params.args.get("barcodeId")
    design_matched_by = params.args.get("design_matched_by")
    image = params.args.get("image")
    detected_issues = params.args.get("detected_issues")
    order = findPrintifyOrder(printifyOrderId)
    if order:
        qcCheck = dict(
            printifyOrderId=printifyOrderId,
            itemId=itemId,
            verification_passed=verification_passed,
            order_id=order_id,
            barcode=barcode,
            design_matched_by=design_matched_by,
            image=image,
            detected_issues=detected_issues,
            orderId = order.id,
            createdAt = datetime.now(tz=pytz.timezone(order.metadata.get("location", {}).get("timezone", "UTC")))
        )
        _, ref = db.collection("printifyQcChecks").add(qcCheck)
        qcCheck['id'] = ref.id
        ref.update(qcCheck)
        return qcCheck
    return {}