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)

[((421, 436), 'flask.Flask', 'Flask', (['__name__'], {}), '(__name__)\n', (426, 436), False, 'from flask import Flask, flash, redirect, render_template, request, session\n'), ((932, 941), 'tempfile.mkdtemp', 'mkdtemp', ([], {}), '()\n', (939, 941), False, 'from tempfile import mkdtemp\n'), ((1024, 1036), 'flask_session.Session', 'Session', (['app'], {}), '(app)\n', (1031, 1036), False, 'from flask_session import Session\n'), ((1091, 1118), 'cs50.SQL', 'SQL', (['"""sqlite:///finance.db"""'], {}), "('sqlite:///finance.db')\n", (1094, 1118), False, 'from cs50 import SQL\n'), ((1154, 1179), 'os.environ.get', 'os.environ.get', (['"""API_KEY"""'], {}), "('API_KEY')\n", (1168, 1179), False, 'import os\n'), ((1316, 1331), 'helpers.apology', 'apology', (['"""TODO"""'], {}), "('TODO')\n", (1323, 1331), False, 'from helpers import apology, login_required, lookup, usd\n'), ((1446, 1461), 'helpers.apology', 'apology', (['"""TODO"""'], {}), "('TODO')\n", (1453, 1461), False, 'from helpers import apology, login_required, lookup, usd\n'), ((1568, 1583), 'helpers.apology', 'apology', (['"""TODO"""'], {}), "('TODO')\n", (1575, 1583), False, 'from helpers import apology, login_required, lookup, usd\n'), ((1697, 1712), 'flask.session.clear', 'session.clear', ([], {}), '()\n', (1710, 1712), False, 'from flask import Flask, flash, redirect, render_template, request, session\n'), ((2843, 2858), 'flask.session.clear', 'session.clear', ([], {}), '()\n', (2856, 2858), False, 'from flask import Flask, flash, redirect, render_template, request, session\n'), ((2905, 2918), 'flask.redirect', 'redirect', (['"""/"""'], {}), "('/')\n", (2913, 2918), False, 'from flask import Flask, flash, redirect, render_template, request, session\n'), ((3034, 3049), 'helpers.apology', 'apology', (['"""TODO"""'], {}), "('TODO')\n", (3041, 3049), False, 'from helpers import apology, login_required, lookup, usd\n'), ((3152, 3167), 'helpers.apology', 'apology', (['"""TODO"""'], {}), "('TODO')\n", (3159, 3167), False, 'from helpers import apology, login_required, lookup, usd\n'), ((3285, 3300), 'helpers.apology', 'apology', (['"""TODO"""'], {}), "('TODO')\n", (3292, 3300), False, 'from helpers import apology, login_required, lookup, usd\n'), ((3433, 3456), 'helpers.apology', 'apology', (['e.name', 'e.code'], {}), '(e.name, e.code)\n', (3440, 3456), False, 'from helpers import apology, login_required, lookup, usd\n'), ((2609, 2622), 'flask.redirect', 'redirect', (['"""/"""'], {}), "('/')\n", (2617, 2622), False, 'from flask import Flask, flash, redirect, render_template, request, session\n'), ((2722, 2751), 'flask.render_template', 'render_template', (['"""login.html"""'], {}), "('login.html')\n", (2737, 2751), False, 'from flask import Flask, flash, redirect, render_template, request, session\n'), ((3400, 3421), 'werkzeug.exceptions.InternalServerError', 'InternalServerError', ([], {}), '()\n', (3419, 3421), False, 'from werkzeug.exceptions import default_exceptions, HTTPException, InternalServerError\n'), ((1872, 1900), 'flask.request.form.get', 'request.form.get', (['"""username"""'], {}), "('username')\n", (1888, 1900), False, 'from flask import Flask, flash, redirect, render_template, request, session\n'), ((1921, 1958), 'helpers.apology', 'apology', (['"""must provide username"""', '(403)'], {}), "('must provide username', 403)\n", (1928, 1958), False, 'from helpers import apology, login_required, lookup, usd\n'), ((2211, 2239), 'flask.request.form.get', 'request.form.get', (['"""username"""'], {}), "('username')\n", (2227, 2239), False, 'from flask import Flask, flash, redirect, render_template, request, session\n'), ((2419, 2467), 'helpers.apology', 'apology', (['"""invalid username and/or password"""', '(403)'], {}), "('invalid username and/or password', 403)\n", (2426, 2467), False, 'from helpers import apology, login_required, lookup, usd\n'), ((2017, 2045), 'flask.request.form.get', 'request.form.get', (['"""password"""'], {}), "('password')\n", (2033, 2045), False, 'from flask import Flask, flash, redirect, render_template, request, session\n'), ((2066, 2103), 'helpers.apology', 'apology', (['"""must provide password"""', '(403)'], {}), "('must provide password', 403)\n", (2073, 2103), False, 'from helpers import apology, login_required, lookup, usd\n'), ((2369, 2397), 'flask.request.form.get', 'request.form.get', (['"""password"""'], {}), "('password')\n", (2385, 2397), False, 'from flask import Flask, flash, redirect, render_template, request, session\n')]