from flask import Flask, request, jsonify, render_template, redirect
import requests, json

app = Flask(__name__, template_folder='./')

## Environment variables

CLIENT_ID = "7377724106160787"
CLIENT_SECRET = "XXXXXX"
CLIENT_SECRET_MP = "XXXXXX"
CLIENT_SECRET_MP_TEST = "XXXXXX"

credentials = {}

def access(platform):
    if request.args.get('code'):
        code = request.args.get('code')
        credentials['client_id'] = CLIENT_ID
        credentials['client_secret'] = CLIENT_SECRET
        credentials['grant_type'] = 'authorization_code'
        credentials['redirect_uri'] = f'https://{request.host}/access/{platform}'
        credentials['code'] = code
        if platform == 'mercadolibre':
            response = requests.post('https://api.mercadolibre.com/oauth/token', json=credentials)
            return "  --- MercadoLibre --- <br><br><br>"+response.text
        elif platform == 'mercadopago':
            del credentials['client_id']
            credentials['client_secret'] = CLIENT_SECRET_MP
            response = requests.post('https://api.mercadopago.com/oauth/token', json=credentials)
            return "  --- MercadoPago --- <br><br><br>"+response.text
        return code
    return "Code not provided."

@app.route('/access/<string:platform>', methods=["GET", "POST"])
def access_to_code(platform):
    response = access(platform)
    return response

def refresh(platform):
    if request.args.get('refresh_token'):
        refresh_token = request.args.get('refresh_token')
        credentials['client_id'] = CLIENT_ID
        credentials['client_secret'] = CLIENT_SECRET
        credentials['grant_type'] = 'refresh_token'
        credentials['refresh_token'] = refresh_token
        if platform == 'mercadolibre':
            response = requests.post('https://api.mercadolibre.com/oauth/token', json=credentials)
            return "  --- MercadoLibre --- <br><br><br>"+response.text
        elif platform == 'mercadopago':
            response = requests.post('https://api.mercadopago.com/oauth/token', json=credentials)
            return "  --- MercadoPago --- <br><br><br>"+response.text
        return refresh_token
    return "Refresh_token not provided."


@app.route('/refresh/<string:platform>', methods=["GET", "POST"])
def refresh_access_token(platform):
    response = refresh(platform)
    return response

@app.route('/notifications', methods=["GET", "POST"])
def notifications_action():
    if request.args:
        args = request.args
        with open("notifications.txt", "a") as notification:
            notification.write(args)
        return "Notifications saved."
    return "No notifications received"

@app.route('/wallet_connect/generate_agreement')
def generate_agreement():
    data = {"return_url": "https://oauth.pfelilpe.com/wallet_connect/confirm_agreement", "agreement_data": {"validation_amount": 3.14, "description": "Test agreement"}}
    response = requests.post("https://api.mercadopago.com/v2/wallet_connect/agreements?client.id="+CLIENT_ID, json=data, headers={"Authorization": "Bearer "+CLIENT_SECRET_MP})
    try:
        return redirect(json.loads(response.text)["agreement_uri"], code=302)
    except:
        print("[X] No se recibió el parámetro agreement_uri")
        return response.text

@app.route('/wallet_connect/confirm_agreement')
def confirm_agreement():
    if request.args.get("agreement") and request.args.get("code"):
        data = {"code": request.args.get("code")}
        response = requests.post(f"https://api.mercadopago.com/v2/wallet_connect/agreements/{request.args.get('agreement')}/payer_token", json=data, headers={"Authorization": "Bearer "+CLIENT_SECRET_MP})
        requests.delete("https://api.mercadopago.com/v2/wallet_connect/agreements/{request.args.get('agreement')}?client_id="+CLIENT_ID, headers={"Authorization": "Bearer "+CLIENT_SECRET_MP})
        return response.text
    else:
        return "You must provide agreement and code parameters."
@app.route('/mercadopago', methods=["GET"])
def mercadopago_pay():
    return render_template('mercadopago.html')

@app.route('/mercadopago/success', methods=["GET"])
def success_payment():
    return "Payment succesfully."

@app.route('/mercadopago/error', methods=["GET"])
def error_payment():
    return "Error on payment."

@app.route('/mercadopago/api/payment', methods=["POST"])
def api_payment():
    import mercadopago
    sdk = mercadopago.SDK(CLIENT_SECRET_MP_TEST)

    payment_data = request.get_json()

    payment_data = {
        "transaction_amount": float(payment_data.get("amount")),
        "token": payment_data.get("token"),
        "installments": 1,
        "description": "Blue shirt",
        "payment_method_id": payment_data.get("paymentMethodId"),
        "issuer_id": payment_data.get("issuerId"),
        "payer": {
            "email": payment_data.get("cardholderEmail")
        }
    }

    payment_response = sdk.payment().create(payment_data)
    payment = payment_response["response"]

    print(payment)
    return payment

@app.route('/headers', methods=["GET"])
def headers():
    return str(request.headers)
