__author__ = "Florian Kaiser"
__copyright__ = "Copyright 2022, Project Aktienbot"
__credits__ = ["Florian Kaiser", "Florian Kellermann", "Linus Eickhof", "Kevin Pauer"]
__license__ = "GPL 3.0"
__version__ = "1.0.1"

import os

from apiflask import APIBlueprint, abort
from app.auth import auth
from app.db import database as db
from app.helper_functions import make_response, get_email_or_abort_401
from app.models import Share
from app.schema import SymbolSchema, SymbolResponseSchema, DeleteSuccessfulSchema, SymbolRemoveSchema

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


@shares_blueprint.route('/share', methods=['POST'])
@shares_blueprint.output(SymbolResponseSchema(many=True), 200)
@shares_blueprint.input(schema=SymbolSchema)
@shares_blueprint.auth_required(auth)
@shares_blueprint.doc(summary="Add new symbol", description="Adds new symbol for current user")
def add_symbol(data):
    email = get_email_or_abort_401()

    # Check if required data is available
    if not check_if_isin_data_exists(data):
        abort(400, message="ISIN missing")

    if not check_if_comment_data_exists(data):
        abort(400, message="Comment missing")

    # Check if share already exists
    check_share = db.session.query(Share).filter_by(isin=data['isin'], email=email).first()
    if check_share is None:
        # Keyword doesn't exist yet for this user -> add it
        new_symbol = Share(
            email=email,
            isin=data['isin'],
            comment=data['comment']
        )
        db.session.add(new_symbol)
        db.session.commit()

        return make_response(new_symbol.as_dict(), 200, "Successfully added symbol")
    else:
        abort(500, "Symbol already exist for this user")


@shares_blueprint.route('/share', methods=['DELETE'])
@shares_blueprint.output(DeleteSuccessfulSchema, 200)
@shares_blueprint.input(schema=SymbolRemoveSchema)
@shares_blueprint.auth_required(auth)
@shares_blueprint.doc(summary="Removes existing symbol", description="Removes existing symbol for current user")
def remove_symbol(data):
    email = get_email_or_abort_401()

    # Check if required data is available
    if not check_if_isin_data_exists(data):
        abort(400, message="ISIN missing")

    # Check if share exists
    check_share = db.session.query(Share).filter_by(isin=data['isin'], email=email).first()
    if check_share is None:
        abort(500, "Symbol doesn't exist for this user")
    else:
        # Delete share
        db.session.query(Share).filter_by(isin=data['isin'], email=email).delete()
        db.session.commit()

        return make_response({}, 200, "Successfully removed symbol")


@shares_blueprint.route('/shares', methods=['GET'])
@shares_blueprint.output(SymbolResponseSchema(many=True), 200)
@shares_blueprint.auth_required(auth)
@shares_blueprint.doc(summary="Returns all symbols", description="Returns all symbols for current user")
def get_symbol():
    email = get_email_or_abort_401()

    return_symbols = []
    symbols = db.session.query(Share).filter_by(email=email).all()

    # If no shares exist for this user -> return empty list
    # Otherwise iterate over all shares, convert them to json and add them to the return list
    if symbols is not None:
        for row in symbols:
            return_symbols.append(row.as_dict())

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


def check_if_isin_data_exists(data):
    if "isin" not in data:
        return False

    if data['isin'] == "" or data['isin'] is None:
        return False

    return True


def check_if_comment_data_exists(data):
    if "comment" not in data:
        return False

    if data['comment'] == "" or data['comment'] is None:
        return False

    return True