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

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, get_user
from app.schema import TelegramIdSchema, UsersSchema

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


@telegram_blueprint.route('/telegram', methods=['POST'])
@telegram_blueprint.output(UsersSchema(many=False), 200)
@telegram_blueprint.input(schema=TelegramIdSchema)
@telegram_blueprint.auth_required(auth)
@telegram_blueprint.doc(summary="Connects telegram user id", description="Connects telegram user id to user account")
def add_keyword(data):
    email = get_email_or_abort_401()

    # Check if request data is valid
    if not check_if_telegram_user_id_data_exists(data):
        abort(400, message="User ID missing")

    query_user = get_user(email)

    # Change user id
    query_user.telegram_user_id = data['telegram_user_id']
    db.session.commit()

    return make_response(query_user.as_dict(), 200, "Successfully connected telegram user")


def check_if_telegram_user_id_data_exists(data):
    if "telegram_user_id" not in data:
        return False

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

    return True
