from functions.Shops import saveShop
from functions.Applications import getAppCredentials
from functions.Users import getUser
from requests_oauthlib import OAuth1Session
from configs.firebase import SERVER_TIMESTAMP
from functions.Etsy import Shops
from oauthlib.oauth1.rfc5849 import SIGNATURE_PLAINTEXT

def authUrl(data):
    user = getUser(data.get("uid"))
    enterpriseId = user.get('enterpriseId')
    application = getAppCredentials(f"1{enterpriseId}")
    redirect_uri = "http://localhost:3000/shops" if data.get('hostname') == "localhost" else f'https://{data.get("hostname")}/shops'
    oauth = OAuth1Session(application.get("apiKey"), client_secret=application.get("apiSecret"), callback_uri=redirect_uri, signature_method=SIGNATURE_PLAINTEXT)
    fetch_response = oauth.fetch_request_token("https://openapi.etsy.com/v2/oauth/request_token")
    return fetch_response


def etsyToken(data:dict):
    ''' Returns Access Token & Access token secret from Etsy'''
    uid, oauthToken, oauthTokenSecret, oauthVerifier = data.get("uid"), data.get("oauthToken"), data.get("oauthTokenSecret"), data.get("oauthVerifier")
    user = getUser(uid)
    enterpriseId = user.get('enterpriseId')
    application = getAppCredentials(f"1{enterpriseId}")
    key = application.get("apiKey")
    secret= application.get("apiSecret")
    oauth = OAuth1Session(key, client_secret=secret, resource_owner_key=oauthToken, resource_owner_secret=oauthTokenSecret, verifier=oauthVerifier)
    oauth_tokens = oauth.fetch_access_token("https://openapi.etsy.com/v2/oauth/access_token")
    oauthToken = oauth_tokens['oauth_token']
    oauthTokenSecret = oauth_tokens['oauth_token_secret']
    shops = Shops.etsyShops(key, secret, oauthToken,oauthTokenSecret)
    shopIds = []
    for shop in shops:
        shop_id = str(shop['shop_id'])
        shopIds.append(saveShop(
            uid=uid,
            platformId="1",
            enterpriseId = enterpriseId,
            platformShopId = shop_id,
            platformName="ETSY", 
            appId = application.get("id"),
            name= shop.get("shop_name"), 
            createdAt = SERVER_TIMESTAMP,
            updatedAt = SERVER_TIMESTAMP, 
            url = shop.get("url"),
            oauthToken = oauthToken,
            oauthTokenSecret=oauthTokenSecret
            ))
    return shopIds
        