from flask import Flask, render_template, redirect, url_for, request
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate
from flask_login import LoginManager, login_required, current_user

from models import db, Student, User, Carburante
from forms import RepostajeForm

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///students.db'
app.config['SECRET_KEY'] = 'mysecret'

db.init_app(app)
migrate = Migrate(app, db)

login_manager = LoginManager()
login_manager.login_view = 'auth.login'
login_manager.init_app(app)


@login_manager.user_loader
def load_user(user_id):
    # since the user_id is just the primary key of our user table, use it in the query for the user
    return User.query.get(int(user_id))

# blueprint for auth routes in our app
from auth import auth as auth_blueprint
app.register_blueprint(auth_blueprint)

@app.route('/')
def index():
    repostajes = Carburante.query.all()
    return render_template('index.html', repostajes=repostajes)

@app.route('/add', methods=['GET', 'POST'])
@login_required
def add_repostaje():
    form = RepostajeForm()
    if form.validate_on_submit():
        precioxlitro = (form.importe.data - form.descuento.data) / form.litros.data
        repostaje = Carburante(fecha=form.fecha.data, vehiculo=form.vehiculo.data, kms=form.kms.data, litros=form.litros.data, descuento=form.descuento.data, importe=form.importe.data, precioxlitro=precioxlitro)
        db.session.add(repostaje)
        db.session.commit()
        return redirect(url_for('index'))
    return render_template('add_record.html', form=form)

@app.route('/edit/<int:id>', methods=['GET', 'POST'])
@login_required
def edit_repostaje(identificador):
    repostaje = Carburante.query.get_or_404(id)
    form = RepostajeForm(obj=repostaje)
    if form.validate_on_submit():
        repostaje.name = form.name.data
        repostaje.age = form.age.data
        repostaje.grade = form.grade.data
        db.session.commit()
        return redirect(url_for('index'))
    return render_template('edit_record.html', form=form, repostaje=repostaje)

@app.route('/delete/<int:id>')
@login_required
def delete_repostaje(id):
    repostaje = Carburante.query.get_or_404(id)
    db.session.delete(repostaje)
    db.session.commit()
    return redirect(url_for('index'))

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