#!flask/bin/python
from flask import Flask, render_template, Response, request
import requests
import json

app = Flask(__name__)

def get_invoice_list():
# Input Variables
    url = 'https://books.zoho.com/api/v3/invoices' #RESTful URL
    authtoken = 'bf3edb14f0a536a594e8c4acf9c0628a' #Authorization token generated by Zoho
    organization_id = '41622462' # organization_id generated by Zoho

    #Get JSON
    auth = {'authtoken':authtoken,'organization_id':organization_id}
    r = requests.get(url,params=auth)
    data = r.json()
    return data

def get_invoice_detail(post):
    # Input Variables
    url = 'https://books.zoho.com/api/v3/invoices/'+post #RESTful URL con invoice_id
    authtoken = 'bf3edb14f0a536a594e8c4acf9c0628a' #Authorization token generated by Zoho
    organization_id = '41622462' # organization_id generated by Zoho

    #Get JSON
    auth = {'authtoken':authtoken,'organization_id':organization_id}
    r = requests.get(url,params=auth)
    invoice = r.json()
    return invoice


@app.route('/')
def index():
    invoice_list = get_invoice_list()
    invoice_json = json.dumps(invoice_list)
    return render_template('index.html', invoice_json=invoice_json)


#falta agregar el argumento para buscar el id del invoice unico y asi encontrar el url correcto.
# def parse_invoice_list():
#     data = get_invoice_list()
#
#     proforma_number = data["invoices"][1]["invoice_number"]
#     fiscal_string = {'invoice_number':proforma_number}
#     return fiscal_string

def translate_product(product):
    if product["tax_percentage"] == 7:
        tasa = 1
    elif product["tax_percentage"] == 0:
        tasa = 0
    elif product["tax_percentage"] == 10:
        tasa = 2
    else:
        tasa = 'error'
    return {"nombre":product['name'],"cantidad":1, "tasa":tasa,"precio":product['item_total']}

@app.route('/create_invoice_json', methods=['POST'])
#falta agregar el argumento para buscar el id del invoice unico y asi encontrar el url correcto.
def create_invoice_json():
    invoice_id = request.form['invoice_id']
    data=get_invoice_detail(invoice_id)
    proforma_number = data["invoice"]["invoice_number"]
    customer_name = data["invoice"]["customer_name"]
    address = data["invoice"]["billing_address"]["address"]
    phone_number = data["invoice"]["customer_name"]
    #ruc = data["invoice"]["customer_name"]
    #print (type(data))
    #for key, value in data.items():
    #    print (value)
    #    print ("")

    products = data["invoice"]["line_items"]
    productos = [translate_product(p) for p in  products]

    fisc = {"factura":{"cliente":{"empresa":"" + customer_name + "","direccion":"" + address + "","telefono":"","ruc":"0"}, "productos":productos}}
    fiscal_json = json.dumps(fisc, ensure_ascii=False).encode('utf8')

    #fiscal_string = '{"factura":{"cliente":{"empresa":'+"\""+customer_name+"\""+',"direccion":"","telefono":"","ruc":"0"}}}'
    #fiscal_json = json.dumps(json.loads(fiscal_string))

    return Response(fiscal_json,
            mimetype='application/json',
            headers={'Content-Disposition':'attachment;filename='+proforma_number+'.json'})

@app.route('/print_gatomalo', methods=['POST'])
def print_gatomalo():
    invoice_id = request.form['invoice_id']
    data=get_invoice_detail(invoice_id)
    proforma_number = data["invoice"]["invoice_number"]
    customer_name = data["invoice"]["customer_name"]
    address = data["invoice"]["billing_address"]["address"]
    phone_number = data["invoice"]["customer_name"]
    #ruc = data["invoice"]["customer_name"]
    #print (type(data))
    #for key, value in data.items():
    #    print (value)
    #    print ("")

    products = data["invoice"]["line_items"]
    productos = [translate_product(p) for p in  products]

    fisc = {"factura":{"cliente":{"empresa":"" + customer_name + "","direccion":"" + address + "","telefono":"","ruc":"0"}, "productos":productos}}
    fiscal_json = json.dumps(fisc, ensure_ascii=False).encode('utf8')

    resp = Response(fiscal_json, status=200, mimetype='application/json')
    resp.headers['Link'] = 'http://localhost:5000/facturas'

    #fiscal_string = '{"factura":{"cliente":{"empresa":'+"\""+customer_name+"\""+',"direccion":"","telefono":"","ruc":"0"}}}'
    #fiscal_json = json.dumps(json.loads(fiscal_string))
    return resp


if __name__ == '__main__':
    app.run(debug=True)
