import json
import os

import requests
from requests_oauthlib import OAuth2Session
from square.client import Client

from functions.Applications import getAppCredentials
from functions.Response import API_Error
from functions.Square.Shops import getSquareMerchants


def squareAuthUrl(data):
    """
    Generates the URL to redirect the user to for authentication.
    """
    currentUser = data.get("currentUser")
    enterpriseId = currentUser.get('enterpriseId')
    app = getAppCredentials("4"+enterpriseId)
    clientId = app.get("apiKey")
    oauth = OAuth2Session(client_id=clientId,
        scope=['ORDERS_READ', 'ORDERS_WRITE', "MERCHANT_PROFILE_READ", "ITEMS_READ", "ITEMS_WRITE",
        "CUSTOMERS_READ", "CUSTOMERS_WRITE", "PAYMENTS_READ"],
        )
    res = oauth.authorization_url('https://connect.squareup.com/oauth2/authorize')
    return dict(url=res[0], state=res[1])


# def squareAuthToken(data):
#     currentUser = data.get("currentUser")
#     enterpriseId = currentUser.get('enterpriseId')
#     app = getAppCredentials("4"+enterpriseId)
#     clientId = app.get("apiKey")
#     clientSecret = app.get("apiSecret")
#     client  = Client(
#         access_token=app.get("accessToken"),
#         square_version="2024-04-17", 
#         )
#     result = client.o_auth.obtain_token(
#         body = {
#             "client_id": clientId,
#             "client_secret": clientSecret,
#             "code": data.get('code'),
#             "grant_type": "authorization_code"
#         }
#         )
#     if result.is_success():
#         # {
#         #     "access_token": "EAAAliFzFQjfCSQWX9A0dEE8VhRaeeW68ggFpCRcniM3WiSouwror3ZZwpV_W7Iw",
#         #     "token_type": "bearer",
#         #     "expires_at": "2024-06-08T09:01:57Z",
#         #     "merchant_id": "MLZ4KEAMAXTQ7",
#         #     "refresh_token": "EQAAljTA5opYG-LiUhU4ArzL4PSw8dZSgXdbP1NXpfdYzi-1svwgFviZqGM8ztLa",
#         #     "short_lived": False
#         #     }
#         data.update(result.body)
#         merchants = getSquareMerchants(data)
#         return merchants
#     else:
#         raise API_Error(result.errors, 500)

def squareAuthToken(data):
    """
    Generates the URL to redirect the user to for authentication.
    """
    currentUser = data.get("currentUser")
    enterpriseId = currentUser.get('enterpriseId')
    app = getAppCredentials("4"+enterpriseId)
    clientId = app.get("apiKey")
    clientSecret = app.get("apiSecret")
    res = requests.post('https://connect.squareup.com/oauth2/token', data=json.dumps({
        'client_id': clientId,
        'client_secret': clientSecret,
        'code': data.get('code'),
        'grant_type': 'authorization_code',
    }),
        headers={
        'Content-Type': 'application/json',
        'Square-Version': '2024-04-17',
        'Authorization': f'Bearer {app.get("accessToken")}'
        })
    # print(res.request.body)
    if res.status_code == 200:
        data.update(res.json())
        merchants = getSquareMerchants(data)
        return merchants
    else:
        raise API_Error(res.json().get("message"), res.status_code, res.json())

def getClient(access_token):
    client = Client(access_token=access_token)
    return client

def getLocations(client):
    result = client.locations.list_locations()
    if result.is_success():
        return result.body.get("locations")
    raise API_Error(result.errors)