from datetime import datetime
from configs.firebase import SERVER_TIMESTAMP
from functions.Applications import getAppCredentials
from functions.Response import API_Error
import requests
from functions.Shops import saveShop

def authUrl(params:dict):
    currentUser =params.get('currentUser')
    uid, enterpriseId, hostname = currentUser.get('uid'), currentUser.get('enterpriseId'), params.get('hostname')
    app = getAppCredentials("8"+enterpriseId)
    url = 'https://login.squarespace.com/api/1/login/oauth/provider/authorize'
    scopes  = ['website.orders', 'website.products', 'website.profiles']
    if app:
        clientId = app.get('apiKey')
        redirect_uri = "https://"+hostname+"/shops/squarespace"
        state = uid
        url = f'{url}?client_id={clientId}&redirect_uri={redirect_uri}&response_type=code&scope={",".join(scopes)}&state={state}&access_type=offline'
        return dict(state = state, url = url)
    raise API_Error(message="No app credentials found", status_code=500)

def authToken(params:dict):
    error, state, code = params.get('error'), params.get('state'), params.get('code')
    if error:
        raise API_Error(message=error, status_code=500)
    currentUser = params.get('currentUser')
    uid, enterpriseId, hostname = currentUser.get('uid'), currentUser.get('enterpriseId'), params.get('hostname')
    app = getAppCredentials(platformId="8", enterpriseId=enterpriseId)
    if app:
        clientId = app.get('apiKey')
        clientSecret = app.get('apiSecret')
        redirect_uri = "https://"+hostname+"/shops/squarespace"
        url = "https://login.squarespace.com/api/1/login/oauth/provider/tokens"
        res = requests.post(url, data=dict(client_id = clientId,
         client_secret = clientSecret, code = code, grant_type = 'authorization_code', redirect_uri = redirect_uri), 
         headers=getHeaders(clientId, clientSecret))
        if res.status_code  in [200, 201]:
            data = res.json()
            token_type, access_token, expires_in, refresh_token = data.get('token_type'), data.get('access_token'), data.get('expires_in'), data.get('refresh_token')
            shop = saveShop(
                    uid=uid,
                    enterpriseId=enterpriseId,
                    platformId="8",
                    platformName="Squarespace",
                    appId=app.get('id'),
                    name=f"{currentUser.get('displayName')}'s Shop",
                    platformShopId =str(datetime.now().timestamp()),
                    createdAt=SERVER_TIMESTAMP,
                    updatedAt=SERVER_TIMESTAMP,
                    accessToken=access_token,
                    refreshToken=refresh_token,
                    tokenType=token_type,
                    expiresIn=expires_in
                )
            return shop
        raise API_Error(message=res.text, status_code=500)
    raise API_Error(message="No app credentials found", status_code=500)
import base64

def getHeaders(clientId, clientSecret):
    return {
        'Authorization': f'Basic {base64.b64encode(f"{clientId}:{clientSecret}".encode()).decode()}',
        'Content-Type': 'application/json',
        'Accept': 'application/json',
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.116 Safari/537.36"
    }

def getAuthHeader(access_token:str):
    return {
        'Authorization': f'Bearer {access_token}',
        'Content-Type': 'application/json',
        'Accept': 'application/json',
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.116 Safari/537.36"
    }