from configs.firebase import SANDBOX, SERVER_TIMESTAMP, db
from functions.Applications import getAppCredentials
import os, base64
import requests
from functions.Shops import saveShop
from functions.Response import API_Error
import requests
from sp_api.api import Orders, Products, ListingsItems, Catalog, CatalogItems, Inventories
def generate_state_parameter():
    random = os.urandom(256)
    state = base64.b64encode(random)
    return (state)

def authUrl(params):
    enterpriseId = params.get("currentUser").get("enterpriseId")
    redirect_uri = f"https://{params.get('hostname')}/shops"
    app = getAppCredentials("7"+enterpriseId)
    appId = app.get("appId")
    # marketplace = app.get("marketplace", dict(id ="US", url = "https://sellercentral-na.amazon.com")).get("url")
    state = generate_state_parameter()
    url = f"https://sellercentral.amazon.com/apps/authorize/consent?application_id={appId}&state={state}&redirect_uri={redirect_uri}"
    return dict(url=url, state=state)

def authToken(params):
    enterpriseId = params.get("currentUser").get("enterpriseId")
    displayName = params.get("currentUser").get("displayName")
    uid = params.get("currentUser").get("uid")
    hostname = params.get("hostname")
    app = getAppCredentials("7"+enterpriseId)
    clientId, clientSecret = app.get("apiKey"), app.get("apiSecret")
    selling_partner_id = params.get("selling_partner_id")
    mws_auth_token = params.get("mws_auth_token")
    spapi_oauth_code = params.get("spapi_oauth_code")
    lwaUrl = "https://api.amazon.com/auth/o2/token"
    lwaBody = dict(
        grant_type="authorization_code",
        client_id=clientId,
        client_secret=clientSecret,
        code=spapi_oauth_code,
        redirect_uri=f"https://{hostname}/shops"
    )
    marketplace = app.get("marketplace", dict(id ="US", url = "https://sellercentral.amazon.com")).get("url")
    res= requests.post(lwaUrl, data=lwaBody, headers={"Content-Type": "application/x-www-form-urlencoded"})
    if res.status_code in [200, 201]:
        data =res.json()
        access_token =data.get("access_token")
        refresh_token =data.get("refresh_token")
        expires_in =data.get("expires_in")
        token_type = data.get("token_type")
        res= requests.post(lwaUrl, data=dict(
            grant_type="refresh_token",
            client_id=clientId,
            client_secret=clientSecret,
            refresh_token=refresh_token
        ), headers={"Content-Type": "application/x-www-form-urlencoded"})
        if res.status_code in [200, 201]:
            data =res.json()
            # print(data)
            access_token =data.get("access_token")
            refresh_token =data.get("refresh_token")
            expires_in =data.get("expires_in")
            token_type = data.get("token_type")
            shop = saveShop(
                uid=uid,
                platformId="7",
                enterpriseId=enterpriseId,
                platformShopId=selling_partner_id,
                appId=app.get("id"),
                createdAt=SERVER_TIMESTAMP,
                updatedAt=SERVER_TIMESTAMP,
                name=params.get("shopName", f"{displayName}'s Amazon Shop"),
                platformName="Amazon",
                url=params.get("shopUrl"),
                accessToken = access_token,
                refreshToken = refresh_token,
                expiresIn = expires_in,
                tokenType = token_type,
                authToken = mws_auth_token,
                oauthCode=spapi_oauth_code,
                marketplace = marketplace
            )
            return shop
    raise API_Error(res.text, res.status_code)

def createCredentials(refreshToken):
    # auth = AWSRequestsAuth(
    #     aws_access_key='AKIA6P6DU7MLWI5ROHR4',
    #     aws_secret_access_key='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',
    #     # aws_token=accessToken,
    #     aws_host='sellingpartnerapi-na.amazon.com',
    #     aws_region='us-east-1',
    #     aws_service='execute-api'
    #     )
    # headers = {'x-amz-access-token': 'Atza|IwEBIHWHEBsppDr6Cb6KTT26ro3LoXa6TwxSA_P7y-FPPwumeR6-AUYXc_pr8Rruafc0-VlAqkbm1e6liI8nXPaAtrbcBBJw4mryvdlhZwyV_OiA0Xc5zcg5OeAJvbQVTKsm02-sui71Yto4i3gOpQI8ZEqOpaPX4yVx21bEy2mWiH0lNvfYhOwx86V0Q6QiN8utNc57ycpS_1vVeNObrkKdhkFMROl54VUc8nGTQ63iv9hOWTtO_sXzTou5idjLAijS41cFfJ4aSMKtzZunYoaTCty33iNcdsp2L521LuyFjSzHAjIE0kW6sUplMWU-vuCHo3nI2Vs971efN3VnOk0FGuqJ'}
    # r = requests.request("GET",'https://sellingpartnerapi-na.amazon.com/products/pricing/v0/price?MarketplaceId=ATVPDKIKX0DER', auth=auth, headers=headers, data=body)
    # print(r.url)
    credentials = dict(
        refresh_token=refreshToken,
        lwa_app_id='amzn1.application-oa2-client.e1a6249812354517bedb25cfa235d7d6',
        lwa_client_secret='a673880d59f6c9316b76aae8edac205851e34fcf2a48a3844b2f700ba7776946',
        aws_access_key='AKIA6P6DU7MLYWOG327O',
        aws_secret_key='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',
        role_arn='arn:aws:iam::996305861399:role/Admin',
    )
    return credentials

# def createCredentials(refresh_token:str,
#             lwa_app_id='amzn1.application-oa2-client.e1a6249812354517bedb25cfa235d7d6',
#             lwa_client_secret='a673880d59f6c9316b76aae8edac205851e34fcf2a48a3844b2f700ba7776946',
#             aws_access_key='AKIA6P6DU7MLYWOG327O',
#             aws_secret_key='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',
#             role_arn='arn:aws:iam::996305861399:role/Admin'
#         ):
#         return dict(
#             refresh_token=refresh_token,
#             lwa_app_id=lwa_app_id,
#             lwa_client_secret=lwa_client_secret,
#             aws_access_key=aws_access_key,
#             aws_secret_key=aws_secret_key,
#             role_arn=role_arn,
#         )