from flask import Flask, request, render_template, redirect, flash, session
from flask_debugtoolbar import DebugToolbarExtension
from models import db, connect_db, Pet
from forms import AddPetForm, EditPetForm

app = Flask(__name__)

app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql:///pets_db'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
app.config['SQLALCHEMY_ECHO'] = False
app.config['SECRET_KEY'] = 'bulb-parabolica'
app.config['DEBUG_TB_INTERCEPT_REDIRECTS'] = False

# SET THIS TO FALSE WHEN RUNNING TESTS
app.config['WTF_CSRF_ENABLED'] = True

debug = DebugToolbarExtension(app)

connect_db(app)

@app.route('/')
def show_home_page():
    """Display all pets on homepage"""
    pets = Pet.query.all()

    return render_template('home.html', pets = pets)

@app.route('/add', methods=['GET', 'POST'])
def add_pet():
    """Add a new pet"""
    form = AddPetForm()
    if form.validate_on_submit():
        name = form.name.data
        species = form.species.data        
        photo_url = form.photo_url.data if form.photo_url.data else None
        age = form.age.data
        notes = form.notes.data

        pet = Pet(name=name, species=species, photo_url=photo_url, age=age, notes=notes)
        db.session.add(pet)
        db.session.commit()

        return redirect('/')
    else:
        return render_template("add.html", form=form)
    
@app.route('/<int:pet_id>', methods=['GET', 'POST'])
def edit_pet(pet_id):
    """Edit an existing pet"""
    pet = Pet.query.get_or_404(pet_id)
    form = EditPetForm(obj=pet)
    # import pdb
    # pdb.set_trace()
    if form.validate_on_submit():
        pet.photo_url = form.photo_url.data if form.photo_url.data else None
        pet.notes = form.notes.data
        pet.is_available = form.is_available.data
        
        db.session.commit()
        return redirect('/')
    else:
        return render_template('pet.html', pet=pet, form=form)