from urllib.parse import urlencode

from woocommerce import API

from configs.env import PROJECT_ID
from configs.firebase import SERVER_TIMESTAMP, db
from functions.Enterprises import getEnterpriseById
from functions.Shops import saveShop


def authUrl(params):
    uid, url, enterpriseId = params.get('currentUser').get('uid'), params.get('url'), params.get('currentUser').get('enterpriseId')
    origin = params.get('hostname')
    noneShops = db.collection("shopsCredentials").where("uid", "==", uid).where("platformId", "==", "3").where("consumerKey", "==", None).where("consumerSecret", "==", None).get()
    for s in noneShops:
        s.reference.delete()
        db.collection("shops").document(s.id).delete()
    enterprise = getEnterpriseById(enterpriseId)
    saveShop(
        uid=uid,
        platformId="3",
        enterpriseId=enterpriseId, 
        platformShopId= url, 
        platformName="WooCommerce", 
        appId="3"+enterpriseId, 
        name=url, 
        url=f"https://{url}", 
        createdAt=SERVER_TIMESTAMP, 
        updatedAt=SERVER_TIMESTAMP, 
        consumerKey = None, 
        consumerSecret=None
        )
    url= f"https://{url}"
    endpoint = '/wc-auth/v1/authorize'
    params = dict(
        app_name = enterprise.get("name", "Riverr") if enterprise else "Riverr",
        scope="read_write",
        user_id = uid,
        return_url = f"{origin}/shops" if origin else "http://localhost:3000/shops",
        callback_url = f"https://riverr-enterprise-integrations-dot-{PROJECT_ID}.uc.r.appspot.com/woocommerce/auth"
    )
    query_string = urlencode(params)
    return dict(url=("%s%s?%s" % (url, endpoint, query_string)))


def saveWooCommerceShop(data):
    uid = data.get("user_id")
    consumerKey = data.get("consumer_key")
    consumerSecret = data.get("consumer_secret")
    ref = db.collection('shopsCredentials').where('uid', '==', uid).where('platformId', '==', "3").where('consumerKey', '==', None).where('consumerSecret', '==', None).get()
    print(len(ref), uid, consumerKey, consumerSecret)
    for doc in ref:
        doc.reference.update(dict(
            consumerKey=consumerKey,
            consumerSecret=consumerSecret
        ))
        print(doc.id)
        return True
    return False


def wooAPI(url, consumerKey, consumerSecret):
    wcapi = API(
        url=url,
        consumer_key=consumerKey,
        consumer_secret=consumerSecret,
        version="wc/v3",
        timeout = 3000
    )
    return wcapi
