__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 datetime
import os
import threading
import time

import investpy
import pandas
import requests
from currency_converter import CurrencyConverter
from dotenv import load_dotenv


def thread_function(s):
    try:
        search_result = investpy.search_quotes(text=s, products=['stocks'], countries=['germany'], n_results=1)

        recent_data = pandas.DataFrame(search_result.retrieve_recent_data())

        stock_price = round(float(recent_data.iloc[-1]["Close"]), 2)

        payload = {
            "isin": s,
            "price": round(float(stock_price), 2),
            "time": datetime.datetime.now().strftime("%Y-%m-%dT%H:%M:%S.000Z")
        }

        requests.post(os.getenv("API_URL") + '/symbol', json=payload, headers={'Authorization': 'Bearer ' + token})
    except RuntimeError:
        my_converter = CurrencyConverter()

        search_result = investpy.search_quotes(text=s, products=['stocks'], n_results=1)

        currency = str(search_result.retrieve_currency())

        recent_data = pandas.DataFrame(search_result.retrieve_recent_data())

        stock_price = my_converter.convert(float(recent_data.iloc[-1]["Close"]), str(currency), 'EUR')

        payload = {
            "isin": s,
            "price": round(float(stock_price), 2),
            "time": datetime.datetime.now().strftime("%Y-%m-%dT%H:%M:%S.000Z")
        }

        requests.post(os.getenv("API_URL") + '/symbol', json=payload, headers={'Authorization': 'Bearer ' + token})


def split(a, n):
    k, m = divmod(len(a), n)
    return (a[i * k + min(i, m):(i + 1) * k + min(i + 1, m)] for i in range(n))


load_dotenv()
username = os.getenv('ADMIN_EMAIL')
password = os.getenv('ADMIN_PASSWORD')

token = requests.post(os.getenv("API_URL") + '/user/login', json={"email": username, "password": password}).json()['data']['token']

response = requests.get(os.getenv("API_URL") + '/symbols', headers={'Authorization': 'Bearer ' + token}).json()['data']

symbols = split(response, int(len(response) / 5))
for symbol_list in symbols:
    for symbol in symbol_list:
        x = threading.Thread(target=thread_function, args=(symbol,))
        x.start()

    time.sleep(10)
