
import datetime
import os
import pickle
import time

from colorama import Fore, init

from .databaseCore import database


class owerview(object):

    def __init__(self):

        init()

        self.p = database()

        self.userid = -1
        self.coin_table = self.p.load_all_coins()

        # load all updates table, runfunction to group by (last in a day)
        self.updates_data = self.p.load_update_all()
        self.__dates_normalization()

        self.user_data_wall_bal = {}

    # update time normalization (save index of last update of a day)
    # saved back in self.update_data
    def __dates_normalization(self):

        try:
            with open("data/tmp/updatesid_last_of_day.pickle", "rb") as f:
                updates_sorted = pickle.load(f)
        except FileNotFoundError:
            updates_sorted = {}

        for x in self.updates_data:

            tmp_date = datetime.datetime.strptime(x[1], "%Y-%m-%d %H:%M:%S")
            tp_day = tmp_date.date()
            str_day = str(tp_day)

            updates_sorted[str_day] = {"date": tmp_date, "id": x[0]}

        self.updates_data = updates_sorted
        # print(str(self.updates_data))

        with open("data/tmp/updatesid_last_of_day.pickle", "wb") as f:
            pickle.dump(updates_sorted, f)

    # user detail view
    def user_view(self, userid, history=False):

        user_balance = self.p.load_user_balance(userid)
        user_wallets = self.p.load_user_wallet(userid)

        self.user_data_wall_bal[0] = user_balance
        self.user_data_wall_bal[1] = user_wallets

        tmp_coinId_list = []
        tmp_coin_price = {}

        # Check if coins and wallets != empty
        if user_balance == [] and user_wallets == []:
            print(
                "No coin balances avaliable.\nEnter coin in balance or\nEnter wallet publicKey")
            time.sleep(5)
            os.system('cls' if os.name == 'nt' else 'clear')
            return 0

        # get all coin id you will need for price
        try:
            for x in user_balance:
                if x[1] in tmp_coinId_list:
                    pass
                else:
                    tmp_coinId_list.append(x[1])
        except:
            pass
        try:
            for x in user_wallets:
                if x[2] in tmp_coinId_list:
                    pass
                else:
                    tmp_coinId_list.append(x[2])
        except:
            pass
        # Quick view if histroy == False
        # Pull last update save in tmp_coin_price[coinID] = { all data }
        if history == False:
            lastupdate = self.p.check_last_update_id()
            coin_price = {}
            # pull only newest update
            for elem in tmp_coinId_list:

                tmp = self.p.load_coin_price_with_mc(elem, lastupdate)

                coin_price[elem] = {"usd": tmp[0], "btc": tmp[1], "mc": tmp[2]}

            tmp_coin_price[lastupdate] = coin_price

            self.__display(tmp_coin_price)
            self.pause()
            return 0

        elif history == True:

            coin_price = {}
            # pull only newest update
            for x in self.updates_data.keys():

                tmp_id = self.updates_data[x]['id']
                tmp_tmp_coin = {}
                for elem in tmp_coinId_list:
                    tmp = self.p.load_coin_price_with_mc(elem, tmp_id)
                    tmp_tmp_coin[elem] = {"usd": tmp[0],
                                          "btc": tmp[1], "mc": tmp[2]}

                coin_price[tmp_id] = tmp_tmp_coin

            # call general view
            self.__display(coin_price)
            self.pause()
            return 0

    def pause(self):
        sss = input("Press ENTER to continue...")
        time.sleep(1)
        os.system('cls' if os.name == 'nt' else 'clear')

    def __display(self, data_dic):
        # you get nested dict if history is true
        # dict[updateID][coinID] = {"usd":? , "btc": ? , "mc": ?}

        usr_bal = self.user_data_wall_bal[0]
        usr_wal = self.user_data_wall_bal[1]

        for i in data_dic:

            tmp_update = data_dic[i]
            date_u = self.p.check_update_date(i)
            print(Fore.YELLOW + "\nWith prices from: " + date_u)
            # Balance outprint
            tot_update_value = 0

            if usr_bal != []:
                print(Fore.MAGENTA + "\nBalance: \n")

                for x in range(len(usr_bal)):

                    tmp_coinid = int(usr_bal[x][1])
                    tmp_name = usr_bal[x][2]
                    tmp_bal_amount = float(usr_bal[x][4])

                    pri_usd = tmp_update[tmp_coinid]['usd']
                    pri_btc = tmp_update[tmp_coinid]['btc']
                    val_usd = tmp_bal_amount * pri_usd
                    val_btc = tmp_bal_amount * pri_btc

                    tot_update_value += val_usd

                    print(Fore.BLUE + "Coin: " + Fore.GREEN + tmp_name + Fore.BLUE + " -balance: " + Fore.GREEN + str(tmp_bal_amount) +
                          Fore.BLUE + " - btc: " + Fore.GREEN + str(pri_btc) + Fore.BLUE + " - usd: " + Fore.GREEN + str(pri_usd))
                    print(Fore.BLUE + "          Total USD/BTC : " + Fore.GREEN + str(val_usd) +
                          Fore.MAGENTA + "$ / " + Fore.GREEN + str(val_btc) + Fore.MAGENTA + " BTCs")
            else:
                pass

            # Wallets out print
            if usr_wal != []:
                print(Fore.MAGENTA + "\nWallets: \n")

                for x in range(len(usr_wal)):

                    tmp_coinid = int(usr_wal[x][2])
                    tmp_name = usr_wal[x][3]
                    tmp_wal_name = usr_wal[x][7]
                    tmp_wal_amount = float(usr_wal[x][5])
                    tmp_wall_addr = usr_wal[x][4]
                    pri_usd = tmp_update[tmp_coinid]['usd']
                    pri_btc = tmp_update[tmp_coinid]['btc']
                    val_usd = tmp_wal_amount * pri_usd
                    val_btc = tmp_wal_amount * pri_btc

                    tot_update_value += val_usd

                    print(Fore.BLUE + "Wallet: " + Fore.GREEN + tmp_wal_name + Fore.BLUE + " - " + Fore.GREEN + tmp_name + Fore.BLUE + " - balance: " + Fore.GREEN + str(
                        tmp_wal_amount) + Fore.BLUE + " - btc: " + Fore.GREEN + str(pri_btc) + Fore.BLUE + " - usd: " + Fore.GREEN + str(pri_usd), end=' ')
                    print(Fore.BLUE + " address: " + Fore.GREEN + tmp_wall_addr + Fore.BLUE + "\n   Total USD / BTC : " +
                          str(val_usd) + Fore.MAGENTA + "$ / " + str(val_btc) + Fore.MAGENTA + " BTCs")
            else:
                pass

            print(Fore.RED + "\nTotal value on date: " + Fore.CYAN + date_u + "   " + Fore.GREEN +
                  str(tot_update_value) + " $\n\n")
            time.sleep(0.8)
