import os

from apiflask import APIBlueprint

from schema import PortfolioResponseSchema
from db import db
from helper_functions import make_response, get_email_or_abort_401
from auth import auth

portfolio_blueprint = APIBlueprint('portfolio', __name__, url_prefix='/api')
__location__ = os.path.realpath(os.path.join(os.getcwd(), os.path.dirname(__file__)))


@portfolio_blueprint.route('/portfolio', methods=['GET'])
@portfolio_blueprint.output(PortfolioResponseSchema(many=True), 200)
@portfolio_blueprint.auth_required(auth)
@portfolio_blueprint.doc(summary="Returns portfolio", description="Returns all shares of current user")
def get_portfolio():
    email = get_email_or_abort_401()

    return_portfolio = []
    transactions = db.session.execute("SELECT symbol, SUM(count), SUM(price), MAX(time) FROM `transactions` WHERE email = '" + email + "' GROUP BY symbol;").all()

    if transactions is not None:
        for row in transactions:
            return_portfolio.append({
                "symbol": row[0],
                "count": row[1],
                # "price": row[2],
                "last_transaction": row[3]
            })

    return make_response(return_portfolio, 200, "Successfully loaded symbols")