
from flask import  Flask, render_template, jsonify, request

from models import *

app = Flask (__name__)
app.config["SQLALCHEMY_DATABASE_URI"]="postgresql://postgres:Mariam1985@localhost:5432/lecture3"
app.config["SQLALCHEMY_TRACK_MODIFICATION"]=False

db.init_app(app)



@app.route("/")
def index():
    #flights = db.execute("SELECT * FROM flights").fetchall()
    flights =Flight.query.all()
    return render_template("index.html", flights=flights)

@app.route("/book", methods=["POST"])
def book():
    """Book a flight."""

    # Get form information.
    name = request.form.get("name")
    try:
        flight_id = int(request.form.get("flight_id"))
    except ValueError:
        return render_template("error.html", message="Invalid flight number.")

    # Make sure flight exists.
     #if db.execute("SELECT * FROM flights WHERE id = :id", {"id": flight_id}).rowcount == 0:
    flight =Flight.query.get(flight_id)
    if flight is None:
        return render_template("error.html", message="No such flight with that id.")
    
    #db.execute("INSERT INTO passengers (name, flight_id) VALUES (:name, :flight_id)",{"name": name, "flight_id": flight_id})
    #crating and adding a new passenget 
    flight.add_passenger(name)

    return render_template("success.html")

@app.route("/flights")
def flights():
    """Lists all flights."""
    #flights = db.execute("SELECT * FROM flights").fetchall()
    flights=Flight.query.all()
   
    return render_template("flights.html", flights=flights)

@app.route("/flights/<int:flight_id>")
def flight_api(flight_id):
    """Lists details about a single flight."""
    #flight = db.execute("SELECT * FROM flights WHERE id = :id", {"id": flight_id}).fetchone()
    # Make sure flight exists.
    flight=Flight.query.get(flight_id)
 
    if flight is None:
        return render_template("error.html", message="No such flight.")

    # Get all passengers.
    #passengers=passenger.query.filter_by(flight_id=flight_id).all()
    passengers=flight.passengers
  
    return render_template("flight.html", flight=flight, passengers=passengers)


@app.route("/api/flights/<int:flight_id>")
def flight(flight_id):
    """Lists details about a single flight."""
    #flight = db.execute("SELECT * FROM flights WHERE id = :id", {"id": flight_id}).fetchone()
    # Make sure flight exists.
    flight=Flight.query.get(flight_id)


    if flight is None:
        return jsonify({"error", "Invalid flight."}), 422

    # Get all passengers.
    #passengers=passenger.query.filter_by(flight_id=flight_id).all()
    passengers=flight.passengers
    names = []
    for passenger in passengers:
        names.append(passenger.name)
    return jsonify({
        "origin":flight.origin,
        "destination":flight.destination,
        "duration":flight.duration,
        "passengers":names
    })
    


if __name__ == "__main__":
    with app.app_context():
        main()
