import os
import datetime

from cs50 import SQL
from flask import Flask, flash, jsonify, 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"""
    dict_username = db.execute("SELECT username FROM users WHERE id = :user_id", user_id=session["user_id"])
    username = dict_username[0]["username"]

    # Amount of cash in account
    bank = db.execute("SELECT cash FROM users WHERE id = :user_id", user_id=session["user_id"])
    print(bank)
    cash = bank[0]["cash"]
    cash = float(cash)

    # Select sum of shares for EVERY Symbol, and total spent
    dict_history = db.execute(
        "SELECT symbol, stock_name, sum(shares) as shares, share_cost as price, sum(price) as tot_total FROM transaction_history WHERE username=:username GROUP BY symbol", username=username)

    for history in dict_history:
        share_values = history["tot_total"]
        share_values = float(share_values)

        symbol = history["symbol"]
        stock_name = history["stock_name"]
        shares = history["shares"]
        price = history["price"]
        tot_total = shares * float(price)

    share_total = db.execute("SELECT sum(price) as tot_total FROM transaction_history WHERE username=:username", username=username)
    print(share_total)
    if share_total[0]["tot_total"] == None:
        total = cash

    else:
        total = share_total[0]["tot_total"] + cash

    headings = ['Symbol', 'Name', 'Shares', 'Price', 'Total']

    # how to dynamically populate table in flask
    return render_template("index.html", headings=headings, dict_history=dict_history, cash=cash, total=total)

@app.route("/buy", methods=["GET", "POST"])
@login_required
def buy():
    """Buy shares of stock"""
    # User reached route via post
    if request.method == "POST":

        if not request.form.get("symbol"):
            return apology("please enter stock symbol")

        if not request.form.get("shares"):
            return apology("must provide number of shares")

        try:
            shares = int(request.form.get("shares"))
        except:
            return apology("shares must be integer, 400")

        if int(shares) <= 0:
            return apology("please enter a positive number")

        symbol = request.form.get("symbol")
        dictionary = lookup(symbol)

        if not dictionary:
            return apology("Invalid symbol")

        shares = request.form.get("shares")
        price = int(shares) * float(dictionary['price'])
        share_cost = dictionary['price']
        stock_name = dictionary['name']
        transacted = datetime.datetime.now()

        dict_username = db.execute("SELECT username FROM users WHERE id = :user_id", user_id=session["user_id"])
        username = dict_username[0]["username"]

        bank = db.execute("SELECT cash FROM users WHERE id = :user_id", user_id=session["user_id"])
        cash = bank[0]["cash"]

        if price > cash:
            return apology("not enough cash")

        rows = db.execute("INSERT INTO transaction_history (username, symbol, shares, price, transacted, stock_name, share_cost) VALUES(?, ?, ?, ?, ?, ?, ?)",
                            username, symbol, shares, price, transacted, stock_name, share_cost)

        # NEED to deduct cost_of_buy from cash (if not enough cash, render an apology)
        rows = db.execute("UPDATE users SET cash = cash - :price WHERE username = :username", price=price, username=username)
        return redirect("/")

    # If user visited Quote via GET:
    else:
        return render_template("buy.html")


@app.route("/history")
@login_required
def history():
    """Show history of transactions"""
    dict_username = db.execute("SELECT username FROM users WHERE id = :user_id", user_id=session["user_id"])
    username = dict_username[0]["username"]

    # Amount of cash in account
    bank = db.execute("SELECT cash FROM users WHERE id = :user_id", user_id=session["user_id"])
    print(bank)
    cash = bank[0]["cash"]
    cash = float(cash)

    # Select sum of shares for EVERY Symbol, and total spent
    dict_history = db.execute(
        "SELECT symbol, stock_name, shares, share_cost as price, transacted FROM transaction_history WHERE username=:username", username=username)

    headings = ['Symbol', 'Name', 'Shares', 'Price', 'Transacted']

    # how to dynamically populate table in flask
    return render_template("history.html", headings=headings, dict_history=dict_history)


@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 = :username",
                          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."""

    # User reached route via post
    if request.method == "POST":

        if not request.form.get("symbol"):
            return apology("please enter stock symbol")

        symbol = request.form.get("symbol")

        dictionary = lookup(symbol)

        if not dictionary:
            return apology("Invalid symbol")

        return render_template("quoted.html", dictionary=dictionary)

    # If user visited Quote via GET:
    else:
        return render_template("quote.html")


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

    # Forget any user_id
    session.clear()

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

        # Query database to check if username is available
        rows = db.execute("SELECT * FROM users WHERE username = :username",
                          username=request.form.get("username"))

        # Returns apology if username is in use
        if not len(rows) != 1:
            return apology("username already in use", 400)

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

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

        elif not request.form.get("confirmation"):
            return apology("must confirm password")

        elif request.form.get("password") != request.form.get("confirmation"):
            return apology("passwords must match")

        elif not request.form.get("username") and not request.form.get("password"):
            return apology("please complete empty fields")

        username = request.form.get("username")
        hashed_password = generate_password_hash(request.form.get("password"), method='pbkdf2:sha256')

        # Insert new username and password_hash into database
        rows = db.execute("INSERT INTO users (username, hash) VALUES(?, ?)", username, hashed_password)

        # Query database to get new user id
        rows = db.execute("SELECT * FROM users WHERE username = :username",
                          username=request.form.get("username"))

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

        return redirect("/")

    else:
        return render_template("register.html")


@app.route("/sell", methods=["GET", "POST"])
@login_required
def sell():
    """Sell shares of stock"""
    # User reached route via post
    if request.method == "POST":

        dict_username = db.execute("SELECT username FROM users WHERE id = :user_id", user_id=session["user_id"])
        username = dict_username[0]["username"]

        if not request.form.get("symbol"):
            return apology("please enter stock symbol")

        if not request.form.get("shares"):
            return apology("must provide number of shares")

        shares = request.form.get("shares")
        if int(shares) <= 0:
            return apology("please enter a positive number")

        symbol = request.form.get("symbol")
        dictionary = lookup(symbol)

        if not dictionary:
            return apology("Invalid symbol")

        shares_to_sell = int(request.form.get("shares"))
        print(shares_to_sell)

        # check if symbol and shares are in db
        dict_check_shares = db.execute(
            "SELECT sum(shares) as tot_shares FROM transaction_history WHERE username = :username AND symbol=:symbol GROUP BY :username, :symbol", username=username, symbol=symbol)
        owned_shares = int(dict_check_shares[0]["tot_shares"])

        if owned_shares == 0:
            return apology("you don't have any, 400")

        if shares_to_sell > owned_shares:
            return apology("ain't got that many shares")

        if shares_to_sell <= owned_shares:
            stock_sold_for_cash = float(shares_to_sell) * float(dictionary['price'])
            neg_shares_to_sell = int(shares_to_sell) * -1
            # Update cash in user table
            rows = db.execute("UPDATE users SET cash = cash + :stock_sold WHERE username = :username",
                                stock_sold=stock_sold_for_cash, username=username)

            stock_sold = float(shares_to_sell) * float(dictionary['price']) * -1
            share_sell_price = float(dictionary['price']) * -1
            stock_name = dictionary['name']
            transacted = datetime.datetime.now()
            # Update transaction_history
            rows = db.execute("INSERT INTO transaction_history (username, symbol, shares, price, transacted, stock_name, share_cost) VALUES(?, ?, ?, ?, ?, ?, ?)",
                                username, symbol, neg_shares_to_sell, stock_sold, transacted, stock_name, share_sell_price)

        return redirect("/")

    # If user visited Quote via GET:
    else:
        dict_username = db.execute("SELECT username FROM users WHERE id = :user_id", user_id=session["user_id"])
        username = dict_username[0]["username"]

        select_symbols = db.execute("SELECT DISTINCT symbol from transaction_history WHERE username = :username", username=username)
        return render_template("sell.html", select_symbols=select_symbols)


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)
