#!/usr/bin/env python
# -*- coding: utf-8 -*-

from bottle import Bottle, run, template, route, request
import json

import sys
import meli
import meli.meli

app_id = sys.argv[1]
secret_key = sys.argv[2]

vmeli = meli.meli.Meli(client_id=app_id,client_secret=secret_key)

app = Bottle()
secret_code = ""
token = ""

@app.route('/')
def authorize():
    global secret_code 
    global token
    secret_code = request.query.get('code')
    if secret_code == None:
    	return "<a href='"+vmeli.auth_url(redirect_URI='http://localhost:4567/')+"'>Enlazar Jazz con Mercadolibre</a>"
    else:
    	vmeli.authorize(secret_code, 'http://localhost:4567/')
    	token = vmeli.access_token
    	return "Autenticacion finalizada correctamente. Puede volver a Jazz.."

@app.route('/getcode')
def getcode():
    return secret_code 

@app.route('/gettoken')
def getcode():
    return token 
    
run(app, host='localhost', port=4567, reloader=True)
