import os

from cs50 import SQL
from flask import Flask, flash, redirect, render_template, request, session
from flask_session import Session
from tempfile import mkdtemp
from werkzeug.exceptions import default_exceptions, HTTPException, InternalServerError
from werkzeug.security import check_password_hash, generate_password_hash

from helpers import apology, login_required, lookup, usd

# Configure application
app = Flask(__name__)

# Ensure templates are auto-reloaded
app.config["TEMPLATES_AUTO_RELOAD"] = True


# Ensure responses aren't cached
@app.after_request
def after_request(response):
    response.headers["Cache-Control"] = "no-cache, no-store, must-revalidate"
    response.headers["Expires"] = 0
    response.headers["Pragma"] = "no-cache"
    return response


# Custom filter
app.jinja_env.filters["usd"] = usd

# Configure session to use filesystem (instead of signed cookies)
app.config["SESSION_FILE_DIR"] = mkdtemp()
app.config["SESSION_PERMANENT"] = False
app.config["SESSION_TYPE"] = "filesystem"
Session(app)

# Configure CS50 Library to use SQLite database
db = SQL("sqlite:///finance.db")

# Make sure API key is set
if not os.environ.get("API_KEY"):
    raise RuntimeError("API_KEY not set")


@app.route("/")
@login_required
def index():
    """Show portfolio of stocks"""
    return apology("TODO")


@app.route("/buy", methods=["GET", "POST"])
@login_required
def buy():
    """Buy shares of stock"""
    return apology("TODO")


@app.route("/history")
@login_required
def history():
    """Show history of transactions"""
    return apology("TODO")


@app.route("/login", methods=["GET", "POST"])
def login():
    """Log user in"""

    # Forget any user_id
    session.clear()

    # User reached route via POST (as by submitting a form via POST)
    if request.method == "POST":

        # Ensure username was submitted
        if not request.form.get("username"):
            return apology("must provide username", 403)

        # Ensure password was submitted
        elif not request.form.get("password"):
            return apology("must provide password", 403)

        # Query database for username
        rows = db.execute("SELECT * FROM users WHERE username = ?", request.form.get("username"))

        # Ensure username exists and password is correct
        if len(rows) != 1 or not check_password_hash(rows[0]["hash"], request.form.get("password")):
            return apology("invalid username and/or password", 403)

        # Remember which user has logged in
        session["user_id"] = rows[0]["id"]

        # Redirect user to home page
        return redirect("/")

    # User reached route via GET (as by clicking a link or via redirect)
    else:
        return render_template("login.html")


@app.route("/logout")
def logout():
    """Log user out"""

    # Forget any user_id
    session.clear()

    # Redirect user to login form
    return redirect("/")


@app.route("/quote", methods=["GET", "POST"])
@login_required
def quote():
    """Get stock quote."""
    return apology("TODO")


@app.route("/register", methods=["GET", "POST"])
def register():
    """Register user"""
    return apology("TODO")


@app.route("/sell", methods=["GET", "POST"])
@login_required
def sell():
    """Sell shares of stock"""
    return apology("TODO")


def errorhandler(e):
    """Handle error"""
    if not isinstance(e, HTTPException):
        e = InternalServerError()
    return apology(e.name, e.code)


# Listen for errors
for code in default_exceptions:
    app.errorhandler(code)(errorhandler)

[((13, 6, 13, 21), 'flask.Flask', 'Flask', ({(13, 12, 13, 20): '__name__'}, {}), '(__name__)', False, 'from flask import Flask, flash, redirect, render_template, request, session\n'), ((32, 33, 32, 42), 'tempfile.mkdtemp', 'mkdtemp', ({}, {}), '()', False, 'from tempfile import mkdtemp\n'), ((35, 0, 35, 12), 'flask_session.Session', 'Session', ({(35, 8, 35, 11): 'app'}, {}), '(app)', False, 'from flask_session import Session\n'), ((38, 5, 38, 32), 'cs50.SQL', 'SQL', ({(38, 9, 38, 31): '"""sqlite:///finance.db"""'}, {}), "('sqlite:///finance.db')", False, 'from cs50 import SQL\n'), ((41, 7, 41, 32), 'os.environ.get', 'os.environ.get', ({(41, 22, 41, 31): '"""API_KEY"""'}, {}), "('API_KEY')", False, 'import os\n'), ((49, 11, 49, 26), 'helpers.apology', 'apology', ({(49, 19, 49, 25): '"""TODO"""'}, {}), "('TODO')", False, 'from helpers import apology, login_required, lookup, usd\n'), ((56, 11, 56, 26), 'helpers.apology', 'apology', ({(56, 19, 56, 25): '"""TODO"""'}, {}), "('TODO')", False, 'from helpers import apology, login_required, lookup, usd\n'), ((63, 11, 63, 26), 'helpers.apology', 'apology', ({(63, 19, 63, 25): '"""TODO"""'}, {}), "('TODO')", False, 'from helpers import apology, login_required, lookup, usd\n'), ((71, 4, 71, 19), 'flask.session.clear', 'session.clear', ({}, {}), '()', False, 'from flask import Flask, flash, redirect, render_template, request, session\n'), ((107, 4, 107, 19), 'flask.session.clear', 'session.clear', ({}, {}), '()', False, 'from flask import Flask, flash, redirect, render_template, request, session\n'), ((110, 11, 110, 24), 'flask.redirect', 'redirect', ({(110, 20, 110, 23): '"""/"""'}, {}), "('/')", False, 'from flask import Flask, flash, redirect, render_template, request, session\n'), ((117, 11, 117, 26), 'helpers.apology', 'apology', ({(117, 19, 117, 25): '"""TODO"""'}, {}), "('TODO')", False, 'from helpers import apology, login_required, lookup, usd\n'), ((123, 11, 123, 26), 'helpers.apology', 'apology', ({(123, 19, 123, 25): '"""TODO"""'}, {}), "('TODO')", False, 'from helpers import apology, login_required, lookup, usd\n'), ((130, 11, 130, 26), 'helpers.apology', 'apology', ({(130, 19, 130, 25): '"""TODO"""'}, {}), "('TODO')", False, 'from helpers import apology, login_required, lookup, usd\n'), ((137, 11, 137, 34), 'helpers.apology', 'apology', ({(137, 19, 137, 25): 'e.name', (137, 27, 137, 33): 'e.code'}, {}), '(e.name, e.code)', False, 'from helpers import apology, login_required, lookup, usd\n'), ((95, 15, 95, 28), 'flask.redirect', 'redirect', ({(95, 24, 95, 27): '"""/"""'}, {}), "('/')", False, 'from flask import Flask, flash, redirect, render_template, request, session\n'), ((99, 15, 99, 44), 'flask.render_template', 'render_template', ({(99, 31, 99, 43): '"""login.html"""'}, {}), "('login.html')", False, 'from flask import Flask, flash, redirect, render_template, request, session\n'), ((136, 12, 136, 33), 'werkzeug.exceptions.InternalServerError', 'InternalServerError', ({}, {}), '()', False, 'from werkzeug.exceptions import default_exceptions, HTTPException, InternalServerError\n'), ((77, 15, 77, 43), 'flask.request.form.get', 'request.form.get', ({(77, 32, 77, 42): '"""username"""'}, {}), "('username')", False, 'from flask import Flask, flash, redirect, render_template, request, session\n'), ((78, 19, 78, 56), 'helpers.apology', 'apology', ({(78, 27, 78, 50): '"""must provide username"""', (78, 52, 78, 55): '(403)'}, {}), "('must provide username', 403)", False, 'from helpers import apology, login_required, lookup, usd\n'), ((85, 68, 85, 96), 'flask.request.form.get', 'request.form.get', ({(85, 85, 85, 95): '"""username"""'}, {}), "('username')", False, 'from flask import Flask, flash, redirect, render_template, request, session\n'), ((89, 19, 89, 67), 'helpers.apology', 'apology', ({(89, 27, 89, 61): '"""invalid username and/or password"""', (89, 63, 89, 66): '(403)'}, {}), "('invalid username and/or password', 403)", False, 'from helpers import apology, login_required, lookup, usd\n'), ((81, 17, 81, 45), 'flask.request.form.get', 'request.form.get', ({(81, 34, 81, 44): '"""password"""'}, {}), "('password')", False, 'from flask import Flask, flash, redirect, render_template, request, session\n'), ((82, 19, 82, 56), 'helpers.apology', 'apology', ({(82, 27, 82, 50): '"""must provide password"""', (82, 52, 82, 55): '(403)'}, {}), "('must provide password', 403)", False, 'from helpers import apology, login_required, lookup, usd\n'), ((88, 70, 88, 98), 'flask.request.form.get', 'request.form.get', ({(88, 87, 88, 97): '"""password"""'}, {}), "('password')", False, 'from flask import Flask, flash, redirect, render_template, request, session\n')]