from flask import render_template, redirect, request, url_for, flash, session, abort, current_app
from flask_login import login_required, login_user, logout_user, current_user
from sqlalchemy import desc

from . import uinvoice
from .forms import ChargeForm, PaymentForm

from ..email import send_email
from .. import db
from ..models import User, Invoice 

#INVOICES
#@uinvoice.route('/charge', methods=['GET', 'POST'])
#@login_required
#def charge():
#    """ generate new invoice based on user request """
#    unpaid_invoices = Order.query.filter_by(user_id=current_user.pid).filter_by(paid=False).all()
#    if unpaid_invoices != []:
#        flash('You have unpaid invoices')
#        return redirect(url_for('uinvoice.documents'))
#    page = { 'title': 'Charge Funds' }
#    form = ChargeForm()
#    if form.validate_on_submit():
#        newinvoice = Order(amount=form.invoice_amount.data, user_id=current_user.pid)
#        db.session.add(newinvoice)
#        db.session.commit()
#        return redirect(url_for('uinvoice.documents'))
#    return render_template('uinvoice/charge.html', page=page, form=form)

@uinvoice.route('/documents', methods=['GET'])
@login_required
def documents():
    page = { 'title': 'Invoice documents' }
    invoices = Invoice.query.filter_by(user_id=current_user.pid).order_by(desc(Invoice.date_created)).all()
    db.session.commit()
    return render_template('uinvoice/documents.html', page=page, documents=invoices)


@uinvoice.route('/order/<int:document_id>', methods=['GET', 'POST'])
@login_required
def order(document_id):
    page = { 'title': 'Preview ' + str(document_id) }
    order = Invoice.query.filter_by(pid=document_id).first()
    db.session.commit()
    #check if document_id is owned by you.
    try:
        if order.user_id != current_user.pid:
            print('WARNING: user {} violates order {}'.format(current_user.pid, order.pid))
            abort(404)
    except:
        abort(404)
    form = PaymentForm()
    if form.validate_on_submit():
        #TODO: contact payment processor
        send_email(current_app.config['MAIL_USERNAME'], current_user.email + ' plati ' + str(order.units * order.unitvalue) + ' v koshnicata.', 'uinvoice/email/adm_payment', user=current_user, order=order )
        order.paid = True
        return redirect(url_for('uinvoice.documents'))
    #except:
    #    abort(404)

    return render_template('uinvoice/invoice.html', page=page, form=form, document=invoice, document_id=document_id)

