import sys
import os
import traceback
import decimal
import datetime as dt
from datetime import datetime, timedelta
import time
import numpy as np
from PyQt5.QtWidgets import *
from PyQt5 import uic
from PyQt5 import QtCore
from PyQt5.QtCore import *
import sip
import matplotlib.pyplot as plt
from matplotlib.figure import Figure
from matplotlib.backends.backend_qt5agg import (FigureCanvasQTAgg as FigureCanvas,
                                                NavigationToolbar2QT as NavigationToolbar)
import matplotlib.dates as mdates
import chelt_plan
from chelt_plan import CheltuieliPlanificate, Income, CheltuieliReale, CheltPlanVSReal, CheltApp, CheltYearlyOnline
from rappmysql.mruser.myusers import Users
from rappmysql.mruser.myusers import DB_Connection as users_db_connection
from rappmysql.cheltuieli.chelt_plan import DB_Connection as chelt_db_connection
from rappmysql.mysqlquerys import connect
import rappmysql

compName = os.getenv('COMPUTERNAME')


class MyApp(QMainWindow):
    def __init__(self, users_db, chelt_db):
        super(MyApp, self).__init__()

        self.users_db_connection = users_db
        self.chelt_db_connection = chelt_db

        path2src, pyFileName = os.path.split(__file__)
        uiFileName = 'chelt_plan.ui'
        path2GUI = os.path.join(path2src, 'GUI', uiFileName)
        Ui_MainWindow, QtBaseClass = uic.loadUiType(path2GUI)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.conf = connect.Config(rappmysql.ini_chelt)
        self.setWindowTitle('{}'.format(self.conf.credentials['database']))

        self.user = None
        self.app = None
        # self.app_without_logged_user = Users(None, rappmysql.ini_users)

        self.ui.GB_when_loged.setVisible(False)
        self.ui.GB_user_options.setVisible(False)
        self.ui.GB_add_one_time_transaction.setVisible(False)
        self.ui.PB_add_on_time_trans.clicked.connect(self.show_add_one_time_transactions)
        # self.prepare_login_window()
        fig1 = Figure()
        self.add_plots(fig1)
        fig2 = Figure()
        self.add_time_plots(fig2, self.ui.loc_de_plot_real_table_dates)
        fig3 = Figure()
        self.add_plotsplan_vs_real(fig3)

        self.ui.PB_login.clicked.connect(self.login_user)
        self.ui.DE_pay_day.setCalendarPopup(True)
        self.ui.PB_export_profile.clicked.connect(self.export_full_profile)
        self.ui.PB_import_profile.clicked.connect(self.import_profile)
        self.ui.PB_import_chelt_backup.clicked.connect(self.import_chelt_backup)
        self.ui.PB_import_real_expenses_csv.clicked.connect(self.import_real_expenses_csv)
        self.ui.PB_DeleteProfile.clicked.connect(self.delete_profile)
        self.ui.PB_fire_req.clicked.connect(self.populate_current_tab_widget)
        self.ui.CBMonths.currentIndexChanged.connect(self.populateDatesInterval)
        self.ui.CB_next_x_days.currentIndexChanged.connect(self.populateDatesInterval)
        self.ui.SB_year.valueChanged.connect(self.populateDatesInterval)
        self.ui.planed_vs_realUnplanned_real_expenses.horizontalHeader().sectionClicked.connect(self.sortUnplanned_real)
        self.ui.planed_vs_realTable.horizontalHeader().sectionClicked.connect(self.sortPlaned_vs_realTable)
        # self.ui.PB_plotTablePie.clicked.connect(self.plotTablePie)
        # self.ui.PB_plotNamePie.clicked.connect(self.plotNamePie)
        # self.ui.PB_Plot.clicked.connect(self.plotGraf)
        self.ui.PB_add_one_time_transactions.clicked.connect(self.add_to_one_time_transactions)
        self.ui.PBComp.clicked.connect(self.compare_real_2plan)
        self.ui.pbImportCSV.clicked.connect(self.importCSV)
        self.ui.PB_backup_planned_expenses.clicked.connect(self.backup_chelt_planned)
        self.ui.PB_backup_real_expenses.clicked.connect(self.backup_real_expenses)
        self.ui.TW_main_user_interface.currentChanged.connect(self.populate_current_tab_widget)
        self.ui.CBOrigTableHead.stateChanged.connect(self.populate_current_tab_widget)
        self.ui.CB_exclude_N26.stateChanged.connect(self.populate_current_tab_widget)
        self.ui.CB_hide_planned_but_not_found.stateChanged.connect(self.populate_current_tab_widget)
        self.ui.CB_hide_planned_and_found_in_real_expenses_table.stateChanged.connect(self.populate_current_tab_widget)
        self.ui.CB_hide_unplanned_real_expenses.stateChanged.connect(self.populate_current_tab_widget)
        # self.ui.CB_allHideIntercontotrans.stateChanged.connect(lambda: (self.prepareTabPlanned(), self.prepareTabReal(), self.prepareTabPlanVsReal()))
        self.ui.CB_allHideIntercontotrans.stateChanged.connect(self.populate_current_tab_widget)

        self.ui.planTable.horizontalHeader().sectionClicked.connect(self.sortTable)
        self.ui.realTable.horizontalHeader().sectionClicked.connect(self.sortTable)
        self.ui.TWsskm.horizontalHeader().sectionClicked.connect(self.sortTable)
        # self.ui.TWdeubnk.horizontalHeader().sectionClicked.connect(self.sortTable)
        # self.ui.TWn26.horizontalHeader().sectionClicked.connect(self.sortTable)
        self.ui.realTable.horizontalHeader().sectionDoubleClicked.connect(self.setFilter)
        self.ui.TWsskm.horizontalHeader().sectionDoubleClicked.connect(self.setFilter)
        # self.ui.TWdeubnk.horizontalHeader().sectionDoubleClicked.connect(self.setFilter)
        # self.ui.TWn26.horizontalHeader().sectionDoubleClicked.connect(self.setFilter)
        self.ui.RB_show_table.toggled.connect(self.populate_current_tab_widget)
        self.ui.RB_show_tree.toggled.connect(self.populate_current_tab_widget)
        self.ui.RB_show_table.toggled.connect(self.populate_current_tab_widget)
        self.ui.RB_show_tree.toggled.connect(self.populate_current_tab_widget)
        self.ui.RB_show_expenses.toggled.connect(self.populate_current_tab_widget)
        self.ui.RB_plot_category.toggled.connect(self.populate_current_tab_widget)
        self.ui.RB_online_conto.toggled.connect(self.populate_current_tab_widget)
        self.ui.CB_available_dates.toggled.connect(self.populate_current_tab_widget)
        self.ui.PB_add_conto.clicked.connect(self.add_conto)
        self.ui.PB_add_transaction.clicked.connect(self.add_transaction)
        self.ui.PB_add_income.clicked.connect(self.add_income)
        self.ui.PB_add_real.clicked.connect(self.add_real)
        self.ui.PB_backup_planned_income.clicked.connect(self.backup_income_planned)
        self.ui.PB_import_income_backup.clicked.connect(self.import_income_backup)
        self.ui.PB_write_sql_yearly_plan.clicked.connect(self.write_sql_yearly_plan)
        self.ui.PB_write_sql_yearly_all.clicked.connect(self.write_sql_yearly_all)
        self.ui.PB_write_real_expenses_yearly_all.clicked.connect(self.write_real_expenses_yearly_all)
        self.ui.PB_write_real_income_yearly_all.clicked.connect(self.write_real_income_yearly_all)

        self.ui.TWsskm.verticalHeader().setContextMenuPolicy(QtCore.Qt.CustomContextMenu)
        self.ui.TWsskm.verticalHeader().customContextMenuRequested.connect(self.contextMenu_TWsskm)
        self.ui.planTable.horizontalHeader().setContextMenuPolicy(QtCore.Qt.CustomContextMenu)
        self.ui.planTable.horizontalHeader().customContextMenuRequested.connect(self.contextMenu_plot_cols_from_table)
        self.ui.planed_vs_realUnplanned_real_expenses.horizontalHeader().setContextMenuPolicy(QtCore.Qt.CustomContextMenu)
        self.ui.planed_vs_realUnplanned_real_expenses.horizontalHeader().customContextMenuRequested.connect(self.contextMenu_plot_cols_from_table)
        self.ui.realTable.horizontalHeader().setContextMenuPolicy(QtCore.Qt.CustomContextMenu)
        self.ui.realTable.horizontalHeader().customContextMenuRequested.connect(self.contextMenu_plot_cols_from_table)
        self.ui.planed_vs_realTable.horizontalHeader().setContextMenuPolicy(QtCore.Qt.CustomContextMenu)
        self.ui.planed_vs_realTable.horizontalHeader().customContextMenuRequested.connect(self.contextMenu_plot_cols_from_table)
        self.ui.realTable.verticalHeader().setContextMenuPolicy(QtCore.Qt.CustomContextMenu)
        self.ui.realTable.verticalHeader().customContextMenuRequested.connect(self.contextMenu_verticalrealTable)
        self.ui.realTableIncome.verticalHeader().setContextMenuPolicy(QtCore.Qt.CustomContextMenu)
        self.ui.realTableIncome.verticalHeader().customContextMenuRequested.connect(self.contextMenu_verticalrealTableIncome)
        self.ui.TWsskm.itemDoubleClicked.connect(self.upload_download_file)
        if compName == 'DESKTOP-5HHINGF' or compName == 'MPCC6995':
            self.ui.LE_user_name.setText('radu')
            self.ui.LE_user_pass.setText('9876')
            # self.ui.LE_user_name.setText('emil')
            # self.ui.LE_user_pass.setText('1234')
            self.login_user()
            # zipFile = r"C:\_Development\Diverse\pypi\radu\cheltuieli\src\cheltuieli\static\backup_profile\000000001\2024_12_18__14_20_50_000000001.zip"
            # self.app_users.import_profile_with_files(zipFile, import_files=False)
            # self.login_user()

    def delete_profile(self):
        message = "Are you sure you want to delete the profile?"
        buttonReply = QMessageBox.question(self, 'Deletion Prompt', message,
                                           QMessageBox.Yes | QMessageBox.No | QMessageBox.Cancel, QMessageBox.Cancel)
        if buttonReply == QMessageBox.Yes:
            self.close()
            self.user.chelt_app.erase_chelt_traces()
        else:
            return

    def export_full_profile(self):
        # expName, _ = QFileDialog.getSaveFileName(self, "Save file", "", "File (*.zip)")
        # expDir = QFileDialog.getExistingDirectory()
        # #print(expDir)
        # if expName:
        if self.ui.CB_export_profile_with_files.isChecked():
            self.user.chelt_app.export_profile(output_dir=None, export_files=True)
        else:
            self.user.chelt_app.export_profile(output_dir=None, export_files=False)

    def backup_chelt_planned(self):
        self.user.chelt_app.export_chelt_plan_sql()

    def backup_real_expenses(self):
        self.user.chelt_app.export_real_expenses_csvs()

    def backup_income_planned(self):
        self.user.chelt_app.export_income_plan_sql()

    def import_profile(self):
        import_files = self.ui.CB_import_profile_with_files.isChecked()
        zip_or_sql_file, _ = QFileDialog.getOpenFileName(self, "Open file", "", "File (*.zip;*.sql)")
        if zip_or_sql_file:
            if zip_or_sql_file.endswith('.zip'):
                zipFile = zip_or_sql_file
                if not self.user:
                    self.app_without_logged_user.import_profile_with_files(zipFile, import_files=import_files)
                    return
                self.user.chelt_app.import_profile(zipFile, import_files=import_files)
                self.login_user()
            elif zip_or_sql_file.endswith('.sql'):
                sqlFile = zip_or_sql_file
                if not self.user:
                    self.app_without_logged_user.import_profile_without_files(sqlFile)
                    return
                self.user.import_profile_without_files(sqlFile)
                self.login_user()

    def import_chelt_backup(self):
        zip_file = self.user.chelt_app.import_profile(self.user.chelt_app.last_chelt_plan_backup_file, import_files=False)
        print('imported', zip_file)
        # if 'cheltuieli' in self.user.applications:
        #     print(25*'cheltuieli')
        #     self.app_planned = CheltuieliPlanificate(chelt_db=self.chelt_db_connection.chelt_db,
        #                                              chelt_plan=self.chelt_db_connection.chelt_plan,
        #                                              yearly_plan=self.chelt_db_connection.yearly_plan,
        #                                              # myAccountsTable=self.chelt_db_connection.myAccountsTable
        #                                              id_users=self.user.id
        #                                              )
            # self.app_planned.prepareTablePlan(currentConto, selectedStartDate, selectedEndDate, hideintercontotrans)
        # self.populate_current_tab_widget()
        return zip_file

    def import_income_backup(self):
        selectedStartDate = self.ui.DEFrom.date().toPyDate()
        selectedEndDate = self.ui.DEBis.date().toPyDate()
        currentConto = self.ui.cbActiveConto.currentText()
        # hideintercontotrans = self.ui.CB_allHideIntercontotrans.isChecked()

        self.user.chelt_app.import_profile(self.user.chelt_app.last_income_plan_backup_file, import_files=False)
        self.chelt_db_connection.refresh_db()
        self.app_planned_income = Income(chelt_db=self.chelt_db_connection.chelt_db,
                                         income_table=self.chelt_db_connection.income_table)
        self.app_planned_income.prepareTablePlan(currentConto, selectedStartDate, selectedEndDate)
        self.populate_current_tab_widget()

    def import_real_expenses_csv(self):
        selectedStartDate = self.ui.DEFrom.date().toPyDate()
        selectedEndDate = self.ui.DEBis.date().toPyDate()
        # currentConto = self.ui.cbActiveConto.currentText()
        hideintercontotrans = self.ui.CB_allHideIntercontotrans.isChecked()

        self.app_reale.import_real_expenses_csvs(self.user.chelt_app.last_real_expenses_backup_file, self.ui.CB_import_real_csvs.isChecked())
        self.chelt_db_connection.refresh_db()
        self.app_reale = CheltuieliReale(chelt_db=self.chelt_db_connection.chelt_db,
                                         myAccountsTable=self.chelt_db_connection.myAccountsTable,
                                         imported_csv=self.chelt_db_connection.imported_csv,
                                         chelt_plan=self.chelt_db_connection.chelt_plan,
                                         plan_vs_real=self.chelt_db_connection.plan_vs_real,
                                         knowntrans=self.chelt_db_connection.knowntrans,
                                         sskm=self.chelt_db_connection.sskm,
                                         deubnk=self.chelt_db_connection.deubnk,
                                         n26=self.chelt_db_connection.n26,
                                         yearly_all=self.chelt_db_connection.yearly_all,
                                         id_users=self.user.id)
        self.app_reale.prepareTableReal_new('all', selectedStartDate, selectedEndDate, hideintercontotrans)
        # self.app_reale.write_real_expenses_yearly_all()
        # self.app_reale.write_real_income_yearly_all()
        # self.chelt_db_connection.refresh_db()
        # self.app_reale = CheltuieliReale(chelt_db=self.chelt_db_connection.chelt_db,
        #                                  myAccountsTable=self.chelt_db_connection.myAccountsTable,
        #                                  imported_csv=self.chelt_db_connection.imported_csv,
        #                                  chelt_plan=self.chelt_db_connection.chelt_plan,
        #                                  plan_vs_real=self.chelt_db_connection.plan_vs_real,
        #                                  knowntrans=self.chelt_db_connection.knowntrans,
        #                                  sskm=self.chelt_db_connection.sskm,
        #                                  deubnk=self.chelt_db_connection.deubnk,
        #                                  n26=self.chelt_db_connection.n26,
        #                                  yearly_all=self.chelt_db_connection.yearly_all,
        #                                  id_users=self.user.id)
        # self.populate_current_tab_widget()

    def login_user(self):
        user_name = self.ui.LE_user_name.text()
        password = self.ui.LE_user_pass.text()

        self.user = Users(user_name=user_name,
                          dataBase=self.users_db_connection.users_db,
                          users_table=self.users_db_connection.users_table,
                          user_apps_table=self.users_db_connection.user_apps_table)
        if self.user.verify_password(password):
            self.ui.GB_when_loged.setVisible(True)
            self.ui.GB_user_options.setVisible(True)
            self.ui.GB_user_pass.setVisible(False)
            self.ui.PB_add_income.setVisible(False)

            self.user.chelt_app = CheltApp(user_id=self.user.id,
                                           chelt_db=self.chelt_db_connection.chelt_db,
                                           chelt_plan=self.chelt_db_connection.chelt_plan,
                                           yearly_plan=self.chelt_db_connection.yearly_plan,
                                           myAccountsTable=self.chelt_db_connection.myAccountsTable,
                                           income_table=self.chelt_db_connection.income_table,
                                           imported_csv=self.chelt_db_connection.imported_csv,
                                           )
            if self.user.chelt_app.has_cheltuieli_real:
                self.app_reale = CheltuieliReale(chelt_db=self.chelt_db_connection.chelt_db,
                                                 myAccountsTable=self.chelt_db_connection.myAccountsTable,
                                                 imported_csv=self.chelt_db_connection.imported_csv,
                                                 chelt_plan=self.chelt_db_connection.chelt_plan,
                                                 plan_vs_real=self.chelt_db_connection.plan_vs_real,
                                                 knowntrans=self.chelt_db_connection.knowntrans,
                                                 sskm=self.chelt_db_connection.sskm,
                                                 deubnk=self.chelt_db_connection.deubnk,
                                                 n26=self.chelt_db_connection.n26,
                                                 yearly_all=self.chelt_db_connection.yearly_all,
                                                 id_users= self.user.id)
                self.ui.PB_add_real.setVisible(False)
            tabWidget = self.ui.TW_main_user_interface
            for i in range(tabWidget.count()):
                tab_name = tabWidget.tabText(i)
                if tab_name == 'Planned Expenses':
                    if 'cheltuieli' in self.user.applications:
                        self.app_planned = CheltuieliPlanificate(chelt_db=self.chelt_db_connection.chelt_db,
                                                                 chelt_plan=self.chelt_db_connection.chelt_plan,
                                                                 yearly_plan=self.chelt_db_connection.yearly_plan,
                                                                 yearly_all=self.chelt_db_connection.yearly_all,
                                                                 # myAccountsTable=self.chelt_db_connection.myAccountsTable
                                                                 id_users=self.user.id)
                    else:
                        tabWidget.setTabEnabled(i, False)
                        message = "User not registered for cheltuieli in user_apps table"
                        QMessageBox.warning(self, 'Permission', message, QMessageBox.Ok)
                        return
                # elif tab_name == "Planned Income":
                #     if self.user.chelt_app.has_planned_income:
                #         self.app_planned_income = Income(chelt_db=self.chelt_db_connection.chelt_db,
                #                                          income_table=self.chelt_db_connection.income_table)
                #     else:
                #         tabWidget.setTabEnabled(i, False)
                #         self.ui.PB_add_income.setVisible(True)
                elif tab_name == "online":
                    self.app_online = CheltYearlyOnline(chelt_db=self.chelt_db_connection.chelt_db,
                                                        yearly_all=self.chelt_db_connection.yearly_all,
                                                        id_users=self.user.id)
                elif tab_name != 'Planned Expenses' and tab_name != "Planned Income" and not self.user.chelt_app.has_cheltuieli_real:
                        tabWidget.setTabEnabled(i, False)
            self.populateCBConto()
            self.populateCBMonths()
            self.populateDatesInterval()
            self.populate_current_tab_widget()
        else:
            print('User not registered in database')

    def populate_current_tab_widget(self):
        print('************************************************************KKKKKKpopulate_current_tab_widget')
        selectedStartDate = self.ui.DEFrom.date().toPyDate()
        selectedEndDate = self.ui.DEBis.date().toPyDate()
        currentConto = self.ui.cbActiveConto.currentText()
        sql_orig_table_head = self.ui.CBOrigTableHead.isChecked()
        hideintercontotrans = self.ui.CB_allHideIntercontotrans.isChecked()
        self.defaultFilter = True
        self.filterList = []

        chelt_type = self.ui.TW_main_user_interface.tabText(self.ui.TW_main_user_interface.currentIndex())
        if chelt_type == 'Planned Expenses':
            if self.user.chelt_app.last_chelt_plan_backup_file:
                self.ui.Lab_last_chelt_plan_backup.setText(self.user.chelt_app.last_chelt_plan_backup)
            # #print('currentConto, selectedStartDate, selectedEndDate, hideintercontotrans', currentConto, selectedStartDate, selectedEndDate, hideintercontotrans)
            self.app_planned.prepareTablePlan(currentConto, selectedStartDate, selectedEndDate, hideintercontotrans)
            # print('self.app_planned.expenses****',self.app_planned.expenses, type(self.app_planned.expenses), self.app_planned.expenses.shape)
            if isinstance(self.app_planned.expenses, np.ndarray) and self.app_planned.expenses.shape == (1, 0):
                # self.ui.GB_when_loged.setVisible(False)
                if self.user.chelt_app.last_chelt_plan_backup_file:
                    message = "no planned expenses, would you like to import the last backup {} ?".format(self.user.chelt_app.last_chelt_plan_backup)
                    buttonReply = QMessageBox.question(self, 'No planned expenses', message, QMessageBox.Yes | QMessageBox.No)
                    if buttonReply == QMessageBox.Yes:
                        zip_file = self.import_chelt_backup()
                        # print(imported)
                        self.chelt_db_connection.refresh_db()
                        self.app_planned = CheltuieliPlanificate(chelt_db=self.chelt_db_connection.chelt_db,
                                                                 chelt_plan=self.chelt_db_connection.chelt_plan,
                                                                 yearly_plan=self.chelt_db_connection.yearly_plan,
                                                                 yearly_all=self.chelt_db_connection.yearly_all,
                                                                 # myAccountsTable=self.chelt_db_connection.myAccountsTable
                                                                 id_users=self.user.id)
                        # self.app_planned.write_sql_yearly_plan()
                        # self.app_planned.write_sql_yearly_all()
                else:
                    message = "no planned expenses, please add transactions"
                    buttonReply = QMessageBox.question(self, 'Deletion Prompt', message, QMessageBox.Yes | QMessageBox.No)
                    if buttonReply == QMessageBox.Yes:
                        self.add_transaction()

                # time.sleep(5)
                self.chelt_db_connection.refresh_db()
                self.app_planned = CheltuieliPlanificate(chelt_db=self.chelt_db_connection.chelt_db,
                                                         chelt_plan=self.chelt_db_connection.chelt_plan,
                                                         yearly_plan=self.chelt_db_connection.yearly_plan,
                                                         yearly_all=self.chelt_db_connection.yearly_all,
                                                         # myAccountsTable=self.chelt_db_connection.myAccountsTable
                                                         id_users=self.user.id)
                # print('currentConto, selectedStartDate, selectedEndDate, hideintercontotrans', currentConto,
                #       selectedStartDate, selectedEndDate, hideintercontotrans)
                self.app_planned.prepareTablePlan(currentConto, selectedStartDate, selectedEndDate, hideintercontotrans)
                # print('ÖÖÖÖÖÖÖÖself.app_planned.expenses', self.app_planned.expenses)
                # print('self.chelt_db_connection.chelt_plan', self.chelt_db_connection.chelt_plan.noOfRows)
            # else:
            #     return

            # print('ÖÖÖÖÖÖÖÖself.app_planned.expenses', self.app_planned.expenses)
            if sql_orig_table_head:
                tableHead = self.app_planned.tableHead
                table = self.app_planned.expenses
            else:
                tableHead, table = chelt_plan.convert_to_display_table(self.app_planned.tableHead,
                                                                       self.app_planned.expenses,
                                                                       self.app_planned.displayExpensesTableHead)
            qt_table_widget = self.ui.planTable
            if self.app_planned.expenses.shape != (1, 0):
                # self.populateExpensesPlan(displayExpensesTableHead)
                if self.ui.RB_show_table.isChecked():
                    self.populateTable(qt_table_widget, tableHead, table)
                    self.ui.TWmnthVSIrreg.setVisible(False)
                    self.ui.planTable.setVisible(True)
                elif self.ui.RB_show_tree.isChecked():
                    self.populateTree()
                    self.ui.planTable.setVisible(False)
                    self.ui.TWmnthVSIrreg.setVisible(True)
                # self.populate_expenses_summary()
                self.prep_2Dplot()
            self.populate_table_summary(self.ui.GB_Planned_expenses_summary, self.app_planned.totals_summary)
        elif chelt_type == 'Planned Income':
            if self.user.chelt_app.last_income_plan_backup_file:
                self.ui.Lab_last_income_plan_backup.setText(self.user.chelt_app.last_income_plan_backup)

            # self.app_planned_income.prepareTablePlan(currentConto, selectedStartDate, selectedEndDate)
            self.app_planned.prepareTablePlan(currentConto, selectedStartDate, selectedEndDate, hideintercontotrans)

            if sql_orig_table_head:
                tableHead = self.app_planned.tableHead
                table = self.app_planned.income
            else:
                tableHead = self.app_planned.displayExpensesTableHead
                tableHead, table = chelt_plan.convert_to_display_table(self.app_planned.tableHead,
                                                                       self.app_planned.income,
                                                                       self.app_planned.displayExpensesTableHead)
            qt_table_widget = self.ui.planTableIncome
            if self.app_planned.income.shape != (1, 0):
                self.populateTable(qt_table_widget, tableHead, table)
                self.ui.TWmnthVSIrreg.setVisible(False)
                self.ui.planTable.setVisible(True)
                # self.populate_income_summary()
        elif chelt_type == 'Real Expenses':
            # self.populateDatesInterval()
            # selectedStartDate = self.ui.DEFrom.date().toPyDate()
            # selectedEndDate = self.ui.DEBis.date().toPyDate()
            # currentConto = self.ui.cbActiveConto.currentText()

            if self.user.chelt_app.last_real_expenses_backup_file:
                self.ui.Lab_last_real_expenses_backup.setText(self.user.chelt_app.last_real_expenses_backup)
            self.app_reale.prepareTableReal_new(currentConto, selectedStartDate, selectedEndDate, hideintercontotrans)
            # print('self.app_reale.realExpenses.shape++++++', self.app_reale.realExpenses.shape)

            # if self.app_reale.realExpenses.shape[1] > 0:
            if self.app_reale.imported_csv_dates:
                values = self.app_reale.vals_for_grafik(self.app_reale.imported_csv_dates, selectedStartDate, selectedEndDate)
                self.populate_grafik_dates(values, self.ui.loc_de_plot_real_table_dates)

            qt_table_widget = self.ui.realTable
            if self.app_reale.realExpenses.shape[1] == 0:
                message = "There were no rows found in interval"
                QMessageBox.warning(self, 'Missing Data', message, QMessageBox.Ok)
                return
            if sql_orig_table_head:
                tableHead = self.app_reale.plan_vs_real.columnsNames
                table = self.app_reale.realExpenses
            else:
                tableHead, table = chelt_plan.convert_to_display_table(self.app_reale.plan_vs_real.columnsNames,
                                                                       self.app_reale.realExpenses,
                                                                       self.app_reale.displayRealTableHead)
            self.populateTable(qt_table_widget, tableHead, table)
            self.populate_table_summary(self.ui.GB_totals_per_conto, self.app_reale.expenses_per_conto)
        elif chelt_type == 'Real Income':
            values = self.app_reale.vals_for_grafik(self.app_reale.imported_csv_dates, selectedStartDate, selectedEndDate)
            self.populate_grafik_dates(values, self.ui.loc_de_plot_incomeper_conto_dates)
            qt_table_widget = self.ui.realTableIncome
            self.app_reale.prepareTableReal_new(currentConto, selectedStartDate, selectedEndDate, hideintercontotrans)
            if self.app_reale.realIncome.shape[1] == 0:
                message = "There were no rows found in interval"
                QMessageBox.warning(self, 'Missing Data', message, QMessageBox.Ok)
                return
            if sql_orig_table_head:
                tableHead = self.app_reale.plan_vs_real.columnsNames
                table = self.app_reale.realIncome
            else:
                tableHead, table = chelt_plan.convert_to_display_table(self.app_reale.plan_vs_real.columnsNames,
                                                                       self.app_reale.realIncome,
                                                                       self.app_reale.displayRealTableHead)
            self.populateTable(qt_table_widget, tableHead, table)
            self.populate_table_summary(self.ui.GB_income_per_conto, self.app_reale.income_per_conto)
        elif chelt_type == 'bank_orig':
            if currentConto == 'all':
                message = 'please select the conto'
                QMessageBox.warning(self, 'Inconsistent Data', message, QMessageBox.Ok)
                return
            values = self.app_reale.vals_for_grafik(self.app_reale.imported_csv_dates, selectedStartDate, selectedEndDate)
            new_values = {currentConto: values[currentConto],
                          'graf_range': values['graf_range']}
            self.populate_grafik_dates(new_values, self.ui.loc_de_plot_bank_orig)
            # self.ui.TrW_columns_2_check.setVisible(False)
            self.app_reale.prepareTableReal_new(currentConto, selectedStartDate, selectedEndDate, hideintercontotrans)
            bank = self.app_reale.get_bank(currentConto)
            qt_table_widget = self.ui.TWsskm
            if bank == 'Stadtsparkasse München':
                bank_table = self.app_reale.sskm
                table_head = self.app_reale.sskm.columnsNames
            elif bank == 'DeutscheBank':
                bank_table = self.app_reale.deubnk
                table_head = self.app_reale.deubnk.columnsNames
            elif bank == 'N26':
                bank_table = self.app_reale.n26
                table_head = self.app_reale.n26.columnsNames
            matches = [('Buchungstag', (selectedStartDate, selectedEndDate)), ('myconto', currentConto)]
            table = bank_table.filterRows(matches)
            table = np.atleast_2d(table)
            if table.shape[1] == 0:
                message = "There were no rows found in interval"
                QMessageBox.warning(self, 'Missing Data', message, QMessageBox.Ok)
                return
            self.populateTable(qt_table_widget, table_head, table)
            self.populate_table_summary(self.ui.GB_per_conto, self.app_reale.expenses_per_conto)
            self.populate_table_summary(self.ui.GB_per_conto_income, self.app_reale.income_per_conto)
            self.populate_table_summary(self.ui.GB_per_conto_totals, self.app_reale.total_income_minus_expenses_per_conto)
        elif chelt_type == 'PlanVsReal':
            puffer_days_to_plann = self.ui.SB_puffer_days_to_plann.value()
            self.app_reale.prepareTableReal_new(currentConto, selectedStartDate, selectedEndDate, hideintercontotrans)
            if self.app_reale.realExpenses.shape[1] == 0:
                message = "There were no rows found in interval"
                QMessageBox.warning(self, 'Missing Data', message, QMessageBox.Ok)
                return
            self.planvsReal = CheltPlanVSReal(chelt_db=self.chelt_db_connection.chelt_db,
                                              chelt_plan=self.chelt_db_connection.chelt_plan,
                                              yearly_plan=self.chelt_db_connection.yearly_plan,
                                              myAccountsTable=self.chelt_db_connection.myAccountsTable,
                                              imported_csv=self.chelt_db_connection.imported_csv,
                                              plan_vs_real=self.chelt_db_connection.plan_vs_real,
                                              knowntrans=self.chelt_db_connection.knowntrans,
                                              sskm=self.chelt_db_connection.sskm,
                                              deubnk=self.chelt_db_connection.deubnk,
                                              n26=self.chelt_db_connection.n26,
                                              yearly_all=self.chelt_db_connection.yearly_all,
                                              currentConto=currentConto,
                                              selectedStartDate=selectedStartDate,
                                              selectedEndDate=selectedEndDate,
                                              hideintercontotrans=hideintercontotrans,
                                              id_users=self.user.id)
            self.planvsReal.find_planned_in_real_expenses_table(hideintercontotrans, puffer_days_to_plann)
            self.planvsReal.find_unplanned_real_expenses(hideintercontotrans, puffer_days_to_plann)
            if self.planvsReal.found_payments_from_planned.shape[0] == 1 and \
                    self.planvsReal.not_found_payments_from_planned.shape[0] == 1 and \
                    self.planvsReal.unplanned_real_expenses.shape[0] == 1:
                return

            min_buchungstag, max_buchungstag = self.app_reale.get_buchungstag_interval(currentConto)
            # if min_buchungstag and max_buchungstag:
            #     self.ui.DE_Buchungstag_min_plvsre.setDate(min_buchungstag)
            #     self.ui.DE_Buchungstag_max_plvsre.setDate(max_buchungstag)

            if not self.ui.CB_hide_planned_and_found_in_real_expenses_table.isChecked():
                qt_table_planed_vs_realTable = self.ui.planed_vs_realTable
                if sql_orig_table_head:
                    tableHead, table = list(self.planvsReal.found_payments_from_planned[0]), \
                                       self.planvsReal.found_payments_from_planned[1:]
                else:
                    tableHead, table = list(self.planvsReal.found_payments_from_planned_display_table[0]), \
                                       self.planvsReal.found_payments_from_planned_display_table[1:]
                self.populateTable(qt_table_planed_vs_realTable, tableHead, table)
            else:
                self.ui.groupBox_18.setVisible(False)

            if not self.ui.CB_hide_planned_but_not_found.isChecked():
                self.ui.groupBox_19.setVisible(True)
                qt_table_planed_vs_realTable_notFound = self.ui.planed_vs_realTable_notFound
                if sql_orig_table_head:
                    tableHead, table = list(self.planvsReal.not_found_payments_from_planned[0]), \
                                       self.planvsReal.not_found_payments_from_planned[1:]
                else:
                    tableHead, table = list(self.planvsReal.not_found_payments_from_planned_display_table[0]), \
                                       self.planvsReal.not_found_payments_from_planned_display_table[1:]
                self.populateTable(qt_table_planed_vs_realTable_notFound, tableHead, table)
            else:
                self.ui.groupBox_19.setVisible(False)

            if not self.ui.CB_hide_unplanned_real_expenses.isChecked():
                qt_table_planed_vs_realTable_notFound = self.ui.planed_vs_realUnplanned_real_expenses
                if sql_orig_table_head:
                    tableHead, table = list(self.planvsReal.unplanned_real_expenses[0]), \
                                       self.planvsReal.unplanned_real_expenses[1:]
                    if self.ui.CB_exclude_N26.isChecked():
                        tableHead, table = list(self.planvsReal.unplanned_real_expenses_without_N26[0]), \
                                           self.planvsReal.unplanned_real_expenses_without_N26[1:]
                else:
                    tableHead, table = list(self.planvsReal.unplanned_real_expenses[0]), \
                                       self.planvsReal.unplanned_real_expenses[1:]
                    if self.ui.CB_exclude_N26.isChecked():
                        tableHead, table = list(self.planvsReal.unplanned_real_expenses_without_N26[0]), \
                                           self.planvsReal.unplanned_real_expenses_without_N26[1:]
                    tableHead, table = chelt_plan.convert_to_display_table(tableHead,
                                                                           table,
                                                                           self.planvsReal.displayPlanVsRealTableHead)

                self.populateTable(qt_table_planed_vs_realTable_notFound, tableHead, table)
            else:
                self.ui.groupBox_20.setVisible(False)
            self.populate_planvsReal_summary()
        elif chelt_type == 'PlanVsReal_plot':
            year = int(self.ui.SB_year.value())
            if selectedStartDate.month == selectedEndDate.month:
                month = chelt_plan.convert_months(selectedStartDate.month)
            else:
                month = self.ui.CBMonths.currentText()
            self.app_online.month = month
            self.app_online.year = year
            self.app_online.conto = currentConto
            self.app_online.hideintercontotrans = hideintercontotrans
            self.app_online.prepareTablePlan()

            self.app_planned.prepareTablePlan(currentConto, selectedStartDate, selectedEndDate, hideintercontotrans)
            self.app_reale.prepareTableReal_new(currentConto, selectedStartDate, selectedEndDate, hideintercontotrans)
            self.prep_2Dplotplan_vs_real()
        elif chelt_type == 'online':
            year = int(self.ui.SB_year.value())
            if selectedStartDate.month == selectedEndDate.month:
                month = chelt_plan.convert_months(selectedStartDate.month)
            else:
                month = self.ui.CBMonths.currentText()
            self.ui.DEFrom.setEnabled(False)
            self.ui.DEBis.setEnabled(False)
            self.ui.CB_next_x_days.setEnabled(False)

            self.ui.GB_calculated.setVisible(False)
            self.ui.GB_from_yearly_table.setVisible(False)
            self.ui.GB_online_real_table_dates.setVisible(False)
            self.ui.GB_yearly_table_dates.setVisible(False)

            if self.ui.CB_calculated.isChecked():
                self.ui.GB_calculated.setVisible(True)
                self.app_planned.prepareTablePlan(currentConto, selectedStartDate, selectedEndDate, hideintercontotrans)
                self.app_reale.prepareTableReal_new(currentConto, selectedStartDate, selectedEndDate,
                                                    hideintercontotrans)
                if self.ui.CB_available_dates.isChecked():
                    self.ui.GB_online_real_table_dates.setVisible(True)
                    self.populate_table_summary(self.ui.GB_online_real_table_dates, self.app_reale.imported_csv_dates)
                if self.ui.RB_show_expenses.isChecked():
                    self.ui.GB_yearly_calc_income.setVisible(False)
                    self.ui.GB_yearly_income.setVisible(False)
                    self.ui.GB_yearly_calc_expenses.setVisible(True)
                    self.ui.GB_yearly_expenses.setVisible(True)
                    if self.ui.RB_online_conto.isChecked():
                        self.ui.GB_planned_expenses_category.setVisible(False)
                        self.ui.GB_real_expenses_category.setVisible(False)
                        self.ui.GB_real_expenses_category_year_before.setVisible(False)
                        self.ui.GB_yearly_planned_expenses_category.setVisible(False)
                        self.ui.GB_yearly_real_expenses_category.setVisible(False)
                        self.ui.GB_yearly_real_expenses_category_year_before.setVisible(False)
                        self.ui.GB_planned_expenses_conto.setVisible(True)
                        self.ui.GB_real_expenses_conto.setVisible(True)
                        self.ui.GB_real_expenses_conto_year_before.setVisible(True)
                        self.ui.GB_yearly_planned_expenses_conto.setVisible(True)
                        self.ui.GB_yearly_real_expenses_conto.setVisible(True)
                        self.ui.GB_yearly_real_expenses_conto_year_before.setVisible(True)
                    elif self.ui.RB_online_category.isChecked():
                        self.ui.GB_planned_expenses_category.setVisible(True)
                        self.ui.GB_real_expenses_category.setVisible(True)
                        self.ui.GB_real_expenses_category_year_before.setVisible(True)
                        self.ui.GB_yearly_planned_expenses_category.setVisible(True)
                        self.ui.GB_yearly_real_expenses_category.setVisible(True)
                        self.ui.GB_yearly_real_expenses_category_year_before.setVisible(True)
                        self.ui.GB_planned_expenses_conto.setVisible(False)
                        self.ui.GB_real_expenses_conto.setVisible(False)
                        self.ui.GB_real_expenses_conto_year_before.setVisible(False)
                        self.ui.GB_yearly_planned_expenses_conto.setVisible(False)
                        self.ui.GB_yearly_real_expenses_conto.setVisible(False)
                        self.ui.GB_yearly_real_expenses_conto_year_before.setVisible(False)
                    ##################Planned Expenses
                    self.ui.label_planned_expenses_totals.setText(str(self.app_planned.tot_val_of_expenses))
                    self.ui.label_real_expenses_totals.setText(str(self.app_reale.tot_val_of_expenses))
                    if self.ui.RB_online_conto.isChecked():
                        self.populate_table_summary(self.ui.GB_planned_expenses_conto, self.app_planned.expenses_per_conto)
                        self.populate_table_summary(self.ui.GB_real_expenses_conto, self.app_reale.expenses_per_conto)
                    elif self.ui.RB_online_category.isChecked():
                        self.populate_table_summary(self.ui.GB_planned_expenses_category, self.app_planned.expenses_per_category)
                        self.populate_table_summary(self.ui.GB_real_expenses_category, self.app_reale.expenses_per_category)
                    if self.ui.CB_real_expenses_year_before.isChecked():
                        startDateYearBefore = selectedStartDate - timedelta(days=365)
                        endDateYearBefore = selectedEndDate - timedelta(days=365)
                        self.app_reale.prepareTableReal_new(currentConto, startDateYearBefore, endDateYearBefore, hideintercontotrans)
                        self.ui.label_real_expenses_totals_year_before.setText(str(self.app_reale.tot_val_of_expenses))
                        if self.ui.RB_online_conto.isChecked():
                            self.populate_table_summary(self.ui.GB_real_expenses_conto_year_before, self.app_reale.expenses_per_conto)
                        elif self.ui.RB_online_category.isChecked():
                            self.populate_table_summary(self.ui.GB_real_expenses_category_year_before, self.app_reale.expenses_per_category)
                elif self.ui.RB_show_income.isChecked():
                    self.ui.GB_yearly_calc_expenses.setVisible(False)
                    self.ui.GB_yearly_calc_income.setVisible(True)
                    self.ui.GB_yearly_expenses.setVisible(False)
                    self.ui.GB_yearly_income.setVisible(True)
                    ##################CALCULATED
                    ##################Planned income
                    self.ui.label_planned_income_totals.setText(str(self.app_planned.tot_val_of_income))
                    self.populate_table_summary(self.ui.GB_planned_income_conto, self.app_planned.income_per_conto)
                    self.populate_table_summary(self.ui.GB_planned_income_category, self.app_planned.income_per_category)
                    ##################Real Income
                    self.ui.label_real_income_totals.setText(str(self.app_reale.tot_val_of_income))
                    self.populate_table_summary(self.ui.GB_real_income_conto, self.app_reale.income_per_conto)
                    self.populate_table_summary(self.ui.GB_real_income_category, self.app_reale.income_per_category)
                    ##################Real Income the year before
                    if self.ui.CB_real_income_year_before.isChecked():
                        startDateYearBefore = selectedStartDate - timedelta(days=365)
                        endDateYearBefore = selectedEndDate - timedelta(days=365)
                        self.app_reale.prepareTableReal_new(currentConto, startDateYearBefore, endDateYearBefore, hideintercontotrans)
                        self.ui.label_real_income_totals_year_before.setText(str(self.app_reale.tot_val_of_income))
                        self.populate_table_summary(self.ui.GB_real_income_conto_year_before, self.app_reale.income_per_conto)
                        self.populate_table_summary(self.ui.GB_real_income_category_year_before, self.app_reale.income_per_category)
            if self.ui.CB_yearly_table.isChecked():
                self.ui.GB_from_yearly_table.setVisible(True)
                self.app_online.month = month
                self.app_online.year = year
                self.app_online.conto = currentConto
                self.app_online.hideintercontotrans = hideintercontotrans
                self.app_online.prepareTablePlan()
                if self.ui.CB_available_dates.isChecked():
                    self.ui.GB_yearly_table_dates.setVisible(True)
                    self.populate_table_summary(self.ui.GB_yearly_table_dates, self.app_online.yearly_available_dates)
                if self.ui.RB_show_expenses.isChecked():
                    self.ui.GB_yearly_income.setVisible(False)
                    self.ui.GB_yearly_expenses.setVisible(True)
                    if self.ui.RB_online_conto.isChecked():
                        self.ui.GB_planned_expenses_category.setVisible(False)
                        self.ui.GB_real_expenses_category.setVisible(False)
                        self.ui.GB_real_expenses_category_year_before.setVisible(False)
                        self.ui.GB_yearly_planned_expenses_category.setVisible(False)
                        self.ui.GB_yearly_real_expenses_category.setVisible(False)
                        self.ui.GB_yearly_real_expenses_category_year_before.setVisible(False)
                        self.ui.GB_planned_expenses_conto.setVisible(True)
                        self.ui.GB_real_expenses_conto.setVisible(True)
                        self.ui.GB_real_expenses_conto_year_before.setVisible(True)
                        self.ui.GB_yearly_planned_expenses_conto.setVisible(True)
                        self.ui.GB_yearly_real_expenses_conto.setVisible(True)
                        self.ui.GB_yearly_real_expenses_conto_year_before.setVisible(True)
                    elif self.ui.RB_online_category.isChecked():
                        self.ui.GB_planned_expenses_category.setVisible(True)
                        self.ui.GB_real_expenses_category.setVisible(True)
                        self.ui.GB_real_expenses_category_year_before.setVisible(True)
                        self.ui.GB_yearly_planned_expenses_category.setVisible(True)
                        self.ui.GB_yearly_real_expenses_category.setVisible(True)
                        self.ui.GB_yearly_real_expenses_category_year_before.setVisible(True)
                        self.ui.GB_planned_expenses_conto.setVisible(False)
                        self.ui.GB_real_expenses_conto.setVisible(False)
                        self.ui.GB_real_expenses_conto_year_before.setVisible(False)
                        self.ui.GB_yearly_planned_expenses_conto.setVisible(False)
                        self.ui.GB_yearly_real_expenses_conto.setVisible(False)
                        self.ui.GB_yearly_real_expenses_conto_year_before.setVisible(False)
                    ##################Planned Expenses
                    self.ui.label_planned_expenses_totals_yearly.setText(str(self.app_online.tot_val_of_planned_expenses))
                    self.ui.label_planned_expenses_average_yearly.setText(str(self.app_online.planned_expenses_average['all']))
                    ##################Real Expenses
                    self.ui.label_real_expenses_totals_yearly.setText(str(self.app_online.tot_val_of_real_expenses))
                    self.ui.label_real_expenses_average_yearly.setText(str(self.app_online.real_expenses_average['all']))
                    if self.ui.CB_real_expenses_year_before.isChecked():
                        app_online_planned_expenses_per_conto = self.app_online.planned_expenses_per_conto.copy()
                        app_online_real_expenses_per_conto = self.app_online.real_expenses_per_conto.copy()
                        app_online_planned_expenses_per_category = self.app_online.planned_expenses_per_category.copy()
                        app_online_real_expenses_per_category = self.app_online.real_expenses_per_category.copy()
                        self.app_online.year = year - 1
                        self.app_online.prepareTablePlan()
                        self.ui.label_real_expenses_totals_yearly_year_before.setText(str(self.app_online.tot_val_of_real_expenses))
                        self.ui.label_real_expenses_average_year_before.setText(str(self.app_online.real_expenses_average['all']))
                        if self.ui.RB_online_conto.isChecked():
                            self.populate_table_summary(self.ui.GB_yearly_planned_expenses_conto, app_online_planned_expenses_per_conto)
                            self.populate_table_summary(self.ui.GB_yearly_real_expenses_conto, app_online_real_expenses_per_conto)
                            self.populate_table_summary(self.ui.GB_yearly_real_expenses_conto_year_before, self.app_online.real_expenses_per_conto)
                        elif self.ui.RB_online_category.isChecked():
                            planned, real, yearbef = self.app_online.get_common_categories_new(app_online_planned_expenses_per_category,
                                                                                          app_online_real_expenses_per_category,
                                                                                          self.app_online.real_expenses_per_category)
                            self.populate_table_summary(self.ui.GB_yearly_planned_expenses_category, planned)
                            self.populate_table_summary(self.ui.GB_yearly_real_expenses_category, real)
                            self.populate_table_summary(self.ui.GB_yearly_real_expenses_category_year_before, yearbef)
                elif self.ui.RB_show_income.isChecked():
                    self.ui.GB_yearly_expenses.setVisible(False)
                    self.ui.GB_yearly_income.setVisible(True)
                    ##################Planned Expenses
                    self.ui.label_planned_income_totals_yearly.setText(str(self.app_online.tot_val_of_planned_income))
                    self.ui.label_planned_income_average_yearly.setText(str(self.app_online.planned_income_average['all']))
                    self.populate_table_summary(self.ui.GB_yearly_planned_income_conto, self.app_online.planned_income_per_conto)
                    self.populate_table_summary(self.ui.GB_yearly_planned_income_category, self.app_online.planned_income_per_category)
                    ##################Real Expenses
                    self.ui.label_real_income_totals_yearly.setText(str(self.app_online.tot_val_of_real_income))
                    self.ui.label_real_income_average_yearly.setText(str(self.app_online.real_income_average['all']))
                    self.populate_table_summary(self.ui.GB_yearly_real_income_conto, self.app_online.real_income_per_conto)
                    self.populate_table_summary(self.ui.GB_yearly_real_income_category, self.app_online.real_income_per_category)
                    ##################Real Expenses the year before
                    if self.ui.CB_real_income_year_before.isChecked():
                        self.app_online.year = year - 1
                        self.app_online.prepareTablePlan()
                        self.ui.label_real_income_totals_yearly_year_before.setText(str(self.app_online.tot_val_of_real_income))
                        self.ui.label_real_income_average_year_before.setText(str(self.app_online.real_income_average['all']))
                        self.populate_table_summary(self.ui.GB_yearly_real_income_conto_year_before, self.app_online.real_income_per_conto)
                        self.populate_table_summary(self.ui.GB_yearly_real_income_category_year_before, self.app_online.real_income_per_category)

    def populateTable(self, qt_table_widget, tableHead, table):
        # sql_orig_table_head = self.ui.CBOrigTableHead.isChecked()
        # if not sql_orig_table_head:
        # #     tableHead = self.app_planned.tableHead
        # #     table = self.app_planned.expenses
        # # else:
        #     tableHead, table = chelt_plan.convert_to_display_table(self.app_planned.tableHead,
        #                                                            self.app_planned.expenses,
        #                                                            self.app_planned.displayExpensesTableHead)

        qt_table_widget.parent().setVisible(True)
        if table.shape[0] == 0:
            qt_table_widget.parent().setVisible(False)
            return
        qt_table_widget.setColumnCount(len(tableHead))
        qt_table_widget.setHorizontalHeaderLabels(tableHead)
        qt_table_widget.setRowCount(table.shape[0])
        for col in range(table.shape[1]):
            # print('qt_table_widget.objectName', qt_table_widget.objectName(), tableHead[col])
            for row in range(table.shape[0]):
                if isinstance(table[row, col], int) or isinstance(table[row, col], float):
                    item = QTableWidgetItem()
                    item.setData(QtCore.Qt.DisplayRole, table[row, col])
                    qt_table_widget.setItem(row, col, item)
                elif isinstance(table[row, col], decimal.Decimal):
                    val = float(table[row, col])
                    item = QTableWidgetItem()
                    item.setData(QtCore.Qt.DisplayRole, val)
                    qt_table_widget.setItem(row, col, item)
                # elif qt_table_widget.objectName() == 'TWsskm' and tableHead[col] == 'path2inp':
                #     # url = bytearray(QUrl.fromLocalFile(pth).toEncoded()).decode()
                #     item = QLabel()
                #     text = "<a href={}>{}</a>".format(str(table[row, col]), str(table[row, col]))
                #     item.setText(text)
                #     # item.setOpenExternalLinks(True)
                #     qt_table_widget.setCellWidget(row, col, item)
                else:
                    item = QTableWidgetItem(str(table[row, col]))
                    qt_table_widget.setItem(row, col, item)
        header = qt_table_widget.horizontalHeader()
        header.setSectionResizeMode(QHeaderView.ResizeToContents)

    def populate_table_summary(self, ui_groupbox, values_dict):
        if not values_dict:
            return
        if ui_groupbox.layout() is not None:
            self.deleteItemsOfLayout(ui_groupbox)
        vbox = QGridLayout()
        for i, (conto, values) in enumerate(values_dict.items()):
            label = QLabel(conto)
            vbox.addWidget(label, i, 0)
            if isinstance(values, tuple) and len(values) == 2:
                tot_val, no_of_transactions = values
                label = QLabel(str(tot_val))
                vbox.addWidget(label, i, 1)
                label = QLabel(str(no_of_transactions))
                vbox.addWidget(label, i, 2)
            else:
                label = QLabel(str(values))
                vbox.addWidget(label, i, 1)

        ui_groupbox.setLayout(vbox)

    # def populate_expenses_summary(self):
    #     # #print('Module: {}, Class: {}, Def: {}'.format(__name__, __class__, sys._getframe().f_code.co_name))
    #     self.ui.LEtotalNoOfTransactions.setText(str(self.app_planned.tot_no_of_expenses))
    #     self.ui.LEtotalValue.setText(str(self.app_planned.tot_val_of_expenses))
    #     self.ui.LEnoOfMonthly.setText(str(self.app_planned.tot_no_of_monthly_expenses))
    #     self.ui.LEtotalMonthly.setText(str(self.app_planned.tot_val_of_monthly_expenses))
    #     self.ui.LEnoOfIrregular.setText(str(self.app_planned.tot_no_of_irregular_expenses))
    #     self.ui.LEirregular.setText(str(self.app_planned.tot_val_of_irregular_expenses))

    def populate_planvsReal_summary(self):
        # #print('Module: {}, Class: {}, Def: {}'.format(__name__, __class__, sys._getframe().f_code.co_name))
        if self.ui.CB_exclude_N26.isChecked():
            self.ui.LE_sum_of_unplanned_real_expenses.setText(
                str(self.planvsReal.sum_of_unplanned_real_expenses_without_n26))
        else:
            self.ui.LE_sum_of_unplanned_real_expenses.setText(str(self.planvsReal.sum_of_unplanned_real_expenses))
        self.ui.LE_total_expenses_planned.setText(str(self.planvsReal.sum_planned))
        self.ui.LE_total_expenses_realised.setText(str(self.planvsReal.sum_realised))
        self.ui.LE_total_no_of_transactions_planned.setText(str(self.planvsReal.sum_realised_from_planned_found))
        self.ui.LE_sum_realised_from_planned_found_in_interval.setText(
            str(self.planvsReal.sum_realised_from_planned_found_in_interval))
        self.ui.LE_planned_but_not_realised.setText(
            str(self.planvsReal.sum_realised_from_not_found_payments_from_planned))
        # self.ui.LE_repeated_rows.setText(str(rows_more_than_one_time))
        self.ui.LE_sum_of_unplanned_real_expenses_without_n26.setText(
            str(self.planvsReal.sum_of_unplanned_real_expenses_without_n26))
        self.ui.LE_sum_of_unplanned_real_expenses_only_n26.setText(
            str(self.planvsReal.sum_of_unplanned_real_expenses_only_n26))
        self.ui.LE_sum_of_unplanned_real_expenses_no_category.setText(
            str(self.planvsReal.sum_of_unplanned_real_expenses_no_category))
        self.ui.LE_sum_of_unplanned_real_expenses_with_category.setText(
            str(self.planvsReal.sum_of_unplanned_real_expenses_with_category))

    def importCSV(self):
        # #print(sys._getframe().f_code.co_name)
        currentConto = self.ui.cbActiveConto.currentText()
        if currentConto == 'all':
            message = 'please select the conto'
            QMessageBox.warning(self, 'Inconsistent Data', message, QMessageBox.Ok)
            return
        inpFile, _ = QFileDialog.getOpenFileName(None, 'Select .csv file', '', 'CSV files (*.csv)')
        if not inpFile:
            return
        self.app_reale.import_CSV_new(currentConto, inpFile)
        self.populate_current_tab_widget()

    def delete_items_of_layout(self):
        # #print('Module: {}, Class: {}, Def: {}'.format(__name__, __class__, sys._getframe().f_code.co_name))
        layout_grupa = self.gb_available_databases.layout()
        if layout_grupa is not None:
            while layout_grupa.count():
                item = layout_grupa.takeAt(0)
                widget = item.widget()
                if widget is not None:
                    widget.setParent(None)
                # else:
                #     delete_items_of_layout(item.layout())
            # sip.delete(layout_grupa)

    def compare_real_2plan(self):
        # #print(sys._getframe().f_code.co_name)
        # self.app_reale.compare2plan()
        self.app_reale.find_all_rows_with_identifications_and_write_to_plan_vs_real_table()
        # self.app_reale.find_knowntrans_in_banks_tables_and_write_to_plan_vs_real_table()
        print('DONE compare_real_2plan')

    def populateTableIncome(self, table):
        # #print(sys._getframe().f_code.co_name)
        self.ui.realTableIncome.setColumnCount(len(self.app_reale.plan_vs_real.columnsNames))
        self.ui.realTableIncome.setHorizontalHeaderLabels(self.app_reale.plan_vs_real.columnsNames)
        self.ui.realTableIncome.setRowCount(table.shape[0])
        for col in range(table.shape[1]):
            for row in range(table.shape[0]):
                if isinstance(table[row, col], int) or isinstance(table[row, col], float):
                    item = QTableWidgetItem()
                    item.setData(QtCore.Qt.DisplayRole, table[row, col])
                elif isinstance(table[row, col], decimal.Decimal):
                    val = float(table[row, col])
                    item = QTableWidgetItem()
                    item.setData(QtCore.Qt.DisplayRole, val)
                else:
                    item = QTableWidgetItem(str(table[row, col]))
                self.ui.realTableIncome.setItem(row, col, item)

        totalVal = 0
        if table.shape[1] > 0:
            allValues = table[:, self.app_reale.plan_vs_real.columnsNames.index('Betrag')].astype(float)
            if None in allValues:
                allValues = allValues[allValues != np.array(None)]
            totalVal = sum(allValues)
        # self.ui.LEtotalNoIncomeTrans.setText(str(len(table)))
        # self.ui.LEtotalIncomeValue.setText(str(totalVal))

    def populateCBMonths(self):
        # print('Module: {}, Class: {}, Def: {}, Caller: {}'.format(__name__, __class__, sys._getframe().f_code.co_name,
        #                                                           sys._getframe().f_back.f_code.co_name))

        self.ui.CBMonths.addItem('month')
        months = [dt.date(2000, m, 1).strftime('%B') for m in range(1, 13)]
        for month in months:
            self.ui.CBMonths.addItem(month)

        self.ui.SB_year.setValue(datetime.now().year)

    def populateCBConto(self):
        # #print('Module: {}, Class: {}, Def: {}'.format(__name__, __class__, sys._getframe().f_code.co_name))
        self.ui.cbActiveConto.addItem('all')
        self.ui.cbActiveConto.addItems(self.app_planned.myContos)
        self.ui.cballContos.addItems(self.app_planned.myContos)

    def populateDatesInterval(self):
        print('Module: {}, Class: {}, Def: {}, Caller: {}'.format(__name__, __class__, sys._getframe().f_code.co_name, sys._getframe().f_back.f_code.co_name))
        # print('self.sender()', self.sender())
        chelt_type = self.ui.TW_main_user_interface.tabText(self.ui.TW_main_user_interface.currentIndex())
        year = int(self.ui.SB_year.value())
        if chelt_type == "Planned Expenses":
            # startDate, lastDayOfMonth = chelt_plan.default_interval()
            startDate, lastDayOfMonth = self.app_planned.default_interval()
        elif chelt_type == "Real Expenses":
            # startDate, lastDayOfMonth = chelt_plan.default_interval()
            startDate, lastDayOfMonth = self.app_planned.default_interval()
        else:
            startDate, lastDayOfMonth = self.app_reale.last_month_of_last_csv()

        if self.ui.CBMonths.currentText() != 'month':
            startDate, lastDayOfMonth = chelt_plan.get_monthly_interval(self.ui.CBMonths.currentText(), year)
        elif self.ui.CBMonths.currentText() == 'month':#and chelt_type == 'online'
            startDate = datetime(year, 1, 1)
            lastDayOfMonth = datetime(year, 12, 31)

        if self.ui.CB_next_x_days.currentText() != '':
            # #print(self.ui.CB_next_x_days.currentText())
            txt = self.ui.CB_next_x_days.currentText()
            days = txt.strip(' days')
            days = int(days)
            lastDayOfMonth = chelt_plan.calculate_today_plus_x_days(days)

        self.ui.DEFrom.setDate(startDate)
        self.ui.DEBis.setDate(lastDayOfMonth)

        self.ui.DEFrom.setCalendarPopup(True)
        self.ui.DEBis.setCalendarPopup(True)

    def populateTree(self):
        self.ui.TWmnthVSIrreg.clear()
        if self.ui.CBOrigTableHead.isChecked():
            tableHead = self.app_planned.tableHead.copy()
            tableHead.insert(0, 'freq')
            self.ui.TWmnthVSIrreg.setHeaderLabels(tableHead)
        else:
            self.ui.TWmnthVSIrreg.setHeaderLabels(['freq', 'name', 'value'])

        monthly_level = QTreeWidgetItem(self.ui.TWmnthVSIrreg)
        monthly_level.setText(0, 'Monthly')
        irregular_level = QTreeWidgetItem(self.ui.TWmnthVSIrreg)
        irregular_level.setText(0, 'Irregular')

        monthlyIndx = np.where(self.app_planned.expenses[:, self.app_planned.tableHead.index('freq')] == 1)
        monthly = self.app_planned.expenses[monthlyIndx]
        for mnth in monthly:
            mnth_item_level = QTreeWidgetItem(monthly_level)
            if self.ui.CBOrigTableHead.isChecked():
                for iii, col in enumerate(mnth):
                    mnth_item_level.setText(iii + 1, str(col))
            else:
                mnth_item_level.setText(1, mnth[self.app_planned.tableHead.index('name')])
                mnth_item_level.setText(2, str(round(mnth[self.app_planned.tableHead.index('value')])))

        totalMonthly = self.app_planned.expenses[monthlyIndx, self.app_planned.tableHead.index('value')][0]
        monthly_level.setText(1, 'Total')
        monthly_level.setText(2, str(round(sum(totalMonthly), 2)))

        irregIndx = np.where(self.app_planned.expenses[:, self.app_planned.tableHead.index('freq')] != 1)
        irregular = self.app_planned.expenses[irregIndx]
        for irr in irregular:
            irr_item_level = QTreeWidgetItem(irregular_level)
            if self.ui.CBOrigTableHead.isChecked():
                for iii, col in enumerate(irr):
                    irr_item_level.setText(iii + 1, str(col))
            else:
                irr_item_level.setText(1, irr[self.app_planned.tableHead.index('name')])
                irr_item_level.setText(2, str(round(irr[self.app_planned.tableHead.index('value')], 2)))

        totalIrreg = self.app_planned.expenses[irregIndx, self.app_planned.tableHead.index('value')][0]
        irregular_level.setText(1, 'Total')
        irregular_level.setText(2, str(round(sum(totalIrreg), 2)))

    def populate_income_summary(self):
        # #print('Module: {}, Class: {}, Def: {}'.format(__name__, __class__, sys._getframe().f_code.co_name))
        self.ui.LE_total_netto.setText(str(self.app_planned_income.netto))
        self.ui.LE_total_taxes.setText(str(self.app_planned_income.taxes))
        self.ui.LE_total_brutto.setText(str(self.app_planned_income.brutto))
        self.ui.LE_salary_uberweisung.setText(str(self.app_planned_income.salary_uberweisung))
        self.ui.LE_salary_abzuge.setText(str(self.app_planned_income.salary_abzuge))
        self.ui.LE_salary_netto.setText(str(self.app_planned_income.salary_netto))
        self.ui.LE_salary_gesetzliche_abzuge.setText(str(self.app_planned_income.salary_gesetzliche_abzuge))
        self.ui.LE_salary_brutto.setText(str(self.app_planned_income.salary_brutto))

    def sortUnplanned_real(self, logical_index):
        # #print(sys._getframe().f_code.co_name)
        header = self.ui.planed_vs_realUnplanned_real_expenses.horizontalHeader()
        order = Qt.DescendingOrder
        if not header.isSortIndicatorShown():
            header.setSortIndicatorShown(True)
        elif header.sortIndicatorSection() == logical_index:
            order = header.sortIndicatorOrder()
        header.setSortIndicator(logical_index, order)
        self.ui.planed_vs_realUnplanned_real_expenses.sortItems(logical_index, order)

    def sortPlaned_vs_realTable(self, logical_index):
        # #print(sys._getframe().f_code.co_name)
        header = self.ui.planed_vs_realTable.horizontalHeader()
        order = Qt.DescendingOrder
        if not header.isSortIndicatorShown():
            header.setSortIndicatorShown(True)
        elif header.sortIndicatorSection() == logical_index:
            order = header.sortIndicatorOrder()
        header.setSortIndicator(logical_index, order)
        self.ui.planed_vs_realTable.sortItems(logical_index, order)

    # def readPlanExpenses(self):
    #     # #print('Module: {}, Class: {}, Def: {}'.format(__name__, __class__, sys._getframe().f_code.co_name))
    #     rows = self.ui.planTable.rowCount()
    #     cols = self.ui.planTable.columnCount()
    #     planExpenseTable = np.empty((rows, cols), dtype=object)
    #     planExpenseTableHead = []
    #     for row in range(rows):
    #         for column in range(cols):
    #             cell = self.ui.planTable.item(row, column)
    #             planExpenseTable[row, column] = cell.text()
    #             colName = self.ui.planTable.horizontalHeaderItem(column).text()
    #             if colName not in planExpenseTableHead:
    #                 planExpenseTableHead.append(colName)
    #
    #     return planExpenseTable, planExpenseTableHead
    #
    # def readPlanIncome(self):
    #     # #print('Module: {}, Class: {}, Def: {}'.format(__name__, __class__, sys._getframe().f_code.co_name))
    #     rows = self.ui.planTableIncome.rowCount()
    #     cols = self.ui.planTableIncome.columnCount()
    #     planIncomeTable = np.empty((rows, cols), dtype=object)
    #     planIncomeTableHead = []
    #     for row in range(rows):
    #         for column in range(cols):
    #             cell = self.ui.planTableIncome.item(row, column)
    #             planIncomeTable[row, column] = cell.text()
    #             colName = self.ui.planTableIncome.horizontalHeaderItem(column).text()
    #             #print('000colName', colName)
    #             if colName not in planIncomeTableHead:
    #                 planIncomeTableHead.append(colName)
    #     #print('****planIncomeTableHead', planIncomeTableHead)
    #     return planIncomeTable, planIncomeTableHead

    # def plotGraf(self):
    #     # #print('Module: {}, Class: {}, Def: {}'.format(__name__, __class__, sys._getframe().f_code.co_name))
    #     realExpenseTable, realExpenseTableHead = self.readPlanExpenses()
    #     planIncomeTable, planIncomeTableHead = self.readPlanIncome()
    #     #print('****planIncomeTableHead', planIncomeTableHead)
    #     x_exp = []
    #     y_exp = []
    #     for date in np.unique(realExpenseTable[:, realExpenseTableHead.index('payDay')]):
    #         indx = np.where(realExpenseTable[:, realExpenseTableHead.index('payDay')] == date)
    #         arr = realExpenseTable[indx, realExpenseTableHead.index('value')].astype(float)
    #         x_exp.append(date)
    #         y_exp.append(abs(sum(arr[0])))
    #
    #     x_inc = []
    #     y_inc = []
    #     for date in np.unique(planIncomeTable[:, planIncomeTableHead.index('payDay')]):
    #         indx = np.where(planIncomeTable[:, planIncomeTableHead.index('payDay')] == date)
    #         arr = planIncomeTable[indx, planIncomeTableHead.index('value')].astype(float)
    #         x_inc.append(date)
    #         y_inc.append(abs(sum(arr[0])))
    #
    #     fig1, ax1 = plt.subplots()
    #     ax1.plot(x_exp, y_exp)
    #     ax1.plot(x_inc, y_inc)
    #     # plt.setp(plt.get_xticklabels(), rotation=30, ha="right")
    #     fig1.autofmt_xdate()
    #     plt.grid()
    #     plt.show()

    def show_add_one_time_transactions(self):
        self.ui.GB_add_one_time_transaction.setVisible(True)

    def add_to_one_time_transactions(self):
        name = self.ui.LE_add_name.text()
        value = float(self.ui.LE_add_value.text())
        myconto = self.ui.cballContos.currentText()
        pay_day = self.ui.DE_pay_day.date().toPyDate()
        self.app_planned.add_one_time_transactions(name, value, myconto, pay_day, self.user.id)

    def sortTable(self, logical_index):
        #print(sys._getframe().f_code.co_name)

        chelt_type = self.ui.TW_main_user_interface.tabText(self.ui.TW_main_user_interface.currentIndex())
        if chelt_type == 'Real Expenses':
            table = self.ui.realTable
        elif chelt_type == 'Planned Expenses':
            table = self.ui.planTable
        elif chelt_type == 'bank_orig':
            table = self.ui.TWsskm
        # elif chelt_type == 'deubnk':
        #     table = self.ui.TWdeubnk
        # elif chelt_type == 'n26':
        #     table = self.ui.TWn26

        header = table.horizontalHeader()
        order = Qt.DescendingOrder
        if not header.isSortIndicatorShown():
            header.setSortIndicatorShown(True)
        elif header.sortIndicatorSection() == logical_index:
            order = header.sortIndicatorOrder()
        header.setSortIndicator(logical_index, order)
        table.sortItems(logical_index, order)

    def setFilter(self, logical_index):
        print('Module: {}, Class: {}, Def: {}, Caller: {}'.format(__name__, __class__, sys._getframe().f_code.co_name, sys._getframe().f_back.f_code.co_name))
        chelt_type = self.ui.TW_main_user_interface.tabText(self.ui.TW_main_user_interface.currentIndex())
        currentConto = self.ui.cbActiveConto.currentText()
        if currentConto != 'all':
            bank = self.app_reale.get_bank(currentConto)

        if chelt_type == 'Real Expenses':
            qt_table = self.ui.realTable
            sql_table = self.app_reale.plan_vs_real
        elif chelt_type == 'Planned Expenses':
            qt_table = self.ui.planTable
            sql_table = self.app_reale.chelt_plan
        elif chelt_type == 'bank_orig':
            qt_table = self.ui.TWsskm
            if bank == 'Stadtsparkasse München':
                sql_table = self.app_reale.sskm
            elif bank == 'DeutscheBank':
                sql_table = self.app_reale.deubnk
            elif bank == 'N26':
                sql_table = self.app_reale.n26
        #
        #
        #     sql_table = self.app_reale.sskm
        # elif chelt_type == 'deubnk':
        #     qt_table = self.ui.TWdeubnk
        #     sql_table = self.app_reale.deubnk
        # elif chelt_type == 'n26':
        #     qt_table = self.ui.TWn26
        #     sql_table = self.app_reale.n26
        # #print('ÖÖÖÖÖÖÖ', qt_table.objectName())
        # #print('logical_index', logical_index)
        colName = qt_table.horizontalHeaderItem(logical_index).text()
        # #print('colName', colName)
        # return
        # colName = self.plan_vs_real.columnsNames[logical_index]
        colType = sql_table.get_column_type(colName)
        if colType == 'int':
            filt = FilterWindow.getIntInterval(colName)
            if not filt:
                return
            if isinstance(filt, tuple):
                minInt, maxInt = filt
                filterVals = (str(minInt), str(maxInt))
            elif isinstance(filt, str):
                filterVals = filt
            self.applyFilter(colName, filterVals)
        elif colType == 'date':
            filt = FilterWindow.getDateInterval(colName)
            if not filt:
                return
            if isinstance(filt, tuple):
                minDate, maxDate = filt
                minDate = minDate.toPyDate()
                maxDate = maxDate.toPyDate()
                filterVals = (str(minDate), str(maxDate))
            elif isinstance(filt, str):
                filterVals = filt
            self.applyFilter(colName, filterVals)
        else:
            header = qt_table.horizontalHeader()
            geom = QtCore.QRect(header.sectionViewportPosition(logical_index), 0, header.sectionSize(logical_index),
                                header.height())
            item = QLineEdit(header)
            item.setGeometry(geom)
            item.show()
            item.setFocus()
            item.editingFinished.connect(lambda: (self.applyFilter(colName, item.text(), qt_table, sql_table),
                                                  item.clear(),
                                                  item.hide(),
                                                  item.deleteLater()))

    def applyFilter(self, colName, filter, qt_table, sql_table):
        print('Module: {}, Class: {}, Def: {}, Caller: {}'.format(__name__, __class__, sys._getframe().f_code.co_name, sys._getframe().f_back.f_code.co_name))
        print('colName, filter, qt_table, sql_table', colName, filter, qt_table, sql_table)
        if filter == '':
            return

        if self.defaultFilter:
            self.ui.lineEditFilterList.clear()
            self.defaultFilter = False

        filterText = self.ui.lineEditFilterList.text()
        if not filterText:
            if isinstance(filter, str):
                filterText += '{}="{}"'.format(colName, filter)
            elif isinstance(filter, tuple):
                filterText += '{} < {} < {}'.format(filter[0], colName, filter[1])
            elif isinstance(filter, list):
                filterText += '{} in {}"'.format(str(filter), colName)
        else:
            if isinstance(filter, str):
                filterText += '; {}="{}"'.format(colName, filter)
            elif isinstance(filter, tuple):
                filterText += '; {} < {} < {}'.format(filter[0], colName, filter[1])
            elif isinstance(filter, list):
                filterText += '; {} in {}"'.format(str(filter), colName)
        self.ui.lineEditFilterList.setText(filterText)
        tup = (colName, filter)
        self.filterList.append(tup)
        selectedStartDate = self.ui.DEFrom.date().toPyDate()
        selectedEndDate = self.ui.DEBis.date().toPyDate()
        match2 = ('Buchungstag', (selectedStartDate, selectedEndDate))
        self.filterList.append(match2)

        currentConto = self.ui.cbActiveConto.currentText()
        if currentConto != 'all':
            match3 = ('myconto', currentConto)
            self.filterList.append(match3)

        # print('***self.filterList', self.filterList)
        filtered_vals = sql_table.filterRows(self.filterList)
        filtered_vals = np.atleast_2d(filtered_vals)
        if filtered_vals.shape == (1, 0):
            filtered_vals = np.empty((0, len(sql_table.columnsNames)))

        sql_orig_table_head = self.ui.CBOrigTableHead.isChecked()
        if qt_table.objectName() == 'realTable':
            # self.populateTableReal(filtered_vals)
            if sql_orig_table_head:
                tableHead = self.app_reale.plan_vs_real.columnsNames
                table = self.app_reale.realExpenses
            else:
                tableHead, table = chelt_plan.convert_to_display_table(self.app_reale.plan_vs_real.columnsNames,
                                                                       filtered_vals,
                                                                       self.app_reale.displayRealTableHead)
            self.populateTable(qt_table, tableHead, table)
        if qt_table.objectName() == 'TWsskm' or qt_table.objectName() == 'TWdeubnk' or qt_table.objectName() == 'TWn26':
            # self.preparesskm(filtered_vals)
            self.populateTable(qt_table, sql_table.columnsNames, filtered_vals)

    # def plotTablePie(self):
    #     # #print('Module: {}, Class: {}, Def: {}'.format(__name__, __class__, sys._getframe().f_code.co_name))
    #     realExpenseTable, realExpenseTableHead = self.readPlanExpenses()
    #     allValues = realExpenseTable[:, realExpenseTableHead.index('value')].astype(float)
    #     if None in allValues:
    #         allValues = allValues[allValues != np.array(None)]
    #     totalVal = sum(allValues)
    #
    #     colTableName = realExpenseTable[:, realExpenseTableHead.index('category')]
    #     labels = []
    #     sizes = []
    #     for table in np.unique(colTableName):
    #         indx = np.where(realExpenseTable[:, realExpenseTableHead.index('category')] == table)
    #         smallArray = realExpenseTable[indx]
    #         values = sum(smallArray[:, realExpenseTableHead.index('value')].astype(float))
    #         txt = '{} = {:.2f}'.format(table, values)
    #         labels.append(txt)
    #         size = (values / totalVal) * 100
    #         sizes.append(size)
    #
    #     fig1, ax1 = plt.subplots()
    #     ax1.pie(sizes, labels=labels, autopct='%1.2f%%', startangle=90)
    #     ax1.axis('equal')
    #     plt.legend(title='Total: {:.2f}'.format(totalVal))
    #
    #     plt.show()

    # def plotNamePie(self):
    #     # #print('Module: {}, Class: {}, Def: {}'.format(__name__, __class__, sys._getframe().f_code.co_name))
    #     realExpenseTable, realExpenseTableHead = self.readPlanExpenses()
    #     allValues = realExpenseTable[:, realExpenseTableHead.index('value')].astype(float)
    #     if None in allValues:
    #         allValues = allValues[allValues != np.array(None)]
    #     totalVal = sum(allValues)
    #
    #     colTableName = realExpenseTable[:, realExpenseTableHead.index('name')]
    #     labels = []
    #     sizes = []
    #     for table in np.unique(colTableName):
    #         indx = np.where(realExpenseTable[:, realExpenseTableHead.index('name')] == table)
    #         smallArray = realExpenseTable[indx]
    #         values = sum(smallArray[:, realExpenseTableHead.index('value')].astype(float))
    #         txt = '{} = {:.2f}'.format(table, values)
    #         labels.append(txt)
    #         size = (values / totalVal) * 100
    #         sizes.append(size)
    #
    #     fig1, ax1 = plt.subplots()
    #     ax1.pie(sizes, labels=labels, autopct='%1.2f%%', startangle=90)
    #     ax1.axis('equal')
    #     plt.legend(title='Total: {:.2f}'.format(totalVal))
    #
    #     plt.show()

    # def plotPie(self, cols):
    #     #print('Module: {}, Class: {}, Def: {}'.format(__name__, __class__, sys._getframe().f_code.co_name))
    #     realExpenseTable, realExpenseTableHead = self.readPlanExpenses()
    #     try:
    #         allValues = realExpenseTable[:, realExpenseTableHead.index(cols[0])].astype(float)
    #         if None in allValues:
    #             allValues = allValues[allValues != np.array(None)]
    #         totalVal = sum(allValues)
    #         values_col = cols[0]
    #         names_col = cols[1]
    #     except:
    #         allValues = realExpenseTable[:, realExpenseTableHead.index(cols[1])].astype(float)
    #         if None in allValues:
    #             allValues = allValues[allValues != np.array(None)]
    #         totalVal = sum(allValues)
    #         values_col = cols[1]
    #         names_col = cols[0]
    #
    #     colTableName = realExpenseTable[:, realExpenseTableHead.index(names_col)]
    #     labels = []
    #     sizes = []
    #     for table in np.unique(colTableName):
    #         indx = np.where(realExpenseTable[:, realExpenseTableHead.index(names_col)] == table)
    #         smallArray = realExpenseTable[indx]
    #         values = sum(smallArray[:, realExpenseTableHead.index(values_col)].astype(float))
    #         txt = '{} = {:.2f}'.format(table, values)
    #         labels.append(txt)
    #         size = (values / totalVal) * 100
    #         sizes.append(size)
    #
    #     fig1, ax1 = plt.subplots()
    #     ax1.pie(sizes, labels=labels, autopct='%1.2f%%', startangle=90)
    #     ax1.axis('equal')
    #     plt.legend(title='Total: {:.2f}'.format(totalVal))
    #
    #     plt.show()

    def prep_2Dplot(self):
        # print('Module: {}, Class: {}, Def: {}'.format(__name__, __class__, sys._getframe().f_code.co_name))
        # realExpenseTable, realExpenseTableHead = self.readPlanExpenses()
        qtablewidget = self.ui.planTable
        realExpenseTable, realExpenseTableHead = self.read_table(qtablewidget)
        allValues = realExpenseTable[:, realExpenseTableHead.index('value')].astype(float)
        if None in allValues:
            allValues = allValues[allValues != np.array(None)]
        totalVal = sum(allValues)

        colTableName = realExpenseTable[:, realExpenseTableHead.index('category')]
        labels = []
        sizes = []
        for table in np.unique(colTableName):
            indx = np.where(realExpenseTable[:, realExpenseTableHead.index('category')] == table)
            smallArray = realExpenseTable[indx]
            values = sum(smallArray[:, realExpenseTableHead.index('value')].astype(float))
            txt = '{} = {:.2f}'.format(table, values)
            labels.append(txt)
            size = (values / totalVal) * 100
            sizes.append(size)

        # print('HHHHHHHHHsizes', sizes, type(sizes))
        # print('HHHHHHHHHlabels', labels, type(labels))
        fig1 = Figure()
        spec5 = fig1.add_gridspec(ncols=1, nrows=2, height_ratios=[1, 1])
        ax1f1 = fig1.add_subplot(spec5[0, 0])  #
        ax1f1.grid(True)
        ax1f1.pie(sizes, labels=labels, autopct='%1.2f%%', startangle=90)
        ax1f1.axis('equal')
        ax1f1.legend()

        ax1f2 = fig1.add_subplot(spec5[1, 0])
        ax1f2.grid(True)

        year = int(self.ui.SB_year.value())
        payments_dict, labels = self.app_planned.prep_yearly_graf(year=year)
        if not payments_dict:
            print('NO yearly table')
            return
        ##########################################################################
        # monthly_plus_irregular = payments_dict['monthly+irregular']
        # monthly = payments_dict['monthly']
        # irregular = payments_dict['irregular']
        x = np.arange(len(labels))  # the label locations
        # width = 0.35  # the width of the bars
        # rects1 = ax1f2.bar(x - width / 2, monthly_plus_irregular, width, label='monthly+irregular')
        # rects2 = ax1f2.bar(x + width / 2, monthly, width, label='monthly')
        ##########################################################################
        sex_counts = {
            'monthly': payments_dict['monthly'],
            'irregular': payments_dict['irregular'],
        }
        bottom = np.zeros(len(labels))
        width = 0.6  # the width of the bars: can also be len(x) sequence
        for sex, sex_count in sex_counts.items():
            # #print(bottom)
            p = ax1f2.bar(labels, sex_count, width, label=sex, bottom=bottom)
            bottom += sex_count

            ax1f2.bar_label(p, label_type='center')
        ##########################################################################

        ax1f2.set_xticks(x)
        ax1f2.set_xticklabels(labels)
        ax1f2.tick_params(axis='x', rotation=55)
        ax1f2.legend()
        self.rmmpl()
        self.add_plots(fig1)

    def add_plots(self, fig):
        # print('Module: {}, Class: {}, Def: {}'.format(__name__, __class__, sys._getframe().f_code.co_name))
        self.canvas = FigureCanvas(fig)
        self.ui.loc_de_plot.addWidget(self.canvas)

    def rmmpl(self):
        # print('Module: {}, Class: {}, Def: {}'.format(__name__, __class__, sys._getframe().f_code.co_name))
        self.ui.loc_de_plot.removeWidget(self.canvas)
        self.canvas.close()

    def populate_grafik_dates(self, values, ui_loc_de_plot):
        # labels = []
        # for row, (bank, interval) in enumerate(values.items()):
        #     if bank == 'graf_range':
        #         continue
        #
        #     # print(row, bank, interval)
        #     start_date, end_date = interval
        #     labels.append(str(start_date))
        #     labels.append(str(end_date))
        # labels.append(str(selectedStartDate))
        # labels.append(str(selectedEndDate))

        fig1 = Figure()
        spec5 = fig1.add_gridspec(ncols=1, nrows=1)
        ax1f1 = fig1.add_subplot(spec5[0, 0])  #
        colors = ['cyan', 'blue', 'orange', 'red', 'grey', 'yellow']
        # colors = plt.colormaps()
        xticks = []
        for row, (bank, interval) in enumerate(values.items()):
            # print('row, bank, dates', row, bank, interval, colors[row])
            if bank == 'graf_range':
                continue

            start_date, end_date =self.app_reale.imported_csv_dates[bank]
            label = '{} {}-{}'.format(bank, start_date, end_date)
            xpos_start, xpos_end = interval
            # print('self.app_reale.imported_csv_dates[bank]', self.app_reale.imported_csv_dates[bank])
            # print('xpos_start, xpos_end', xpos_start, xpos_end)
            xticks.append(xpos_start)
            xticks.append(xpos_end)
            barh_length = xpos_end - xpos_start
            ax1f1.broken_barh([(xpos_start, barh_length)], (row, 1), label=label,facecolors='tab:{}'.format(colors[row]))#
            # ax1f1.broken_barh([(xpos_start, xpos_end)], (row, 1), facecolors=colors[row % len(colors)], label=label)
            # dates.sort()
            #
            # # Calculate the width of the bar using the date difference
            # start_date = mdates.date2num(dates[0])  # Convert start date to numerical
            # end_date = mdates.date2num(dates[-1])  # Convert end date to numerical
            # width = end_date - start_date  # Width is the difference between end and start
            #
            # # Draw a broken bar for the bank
            # print(start_date, width)
            # ax1f1.broken_barh([(start_date, width)], (row, 0.8), facecolors='tab:{}'.format(colors[row]), label=bank)
        # self.ax.set_yticks(np.arange(len(data)))
        # self.ax.set_yticklabels(data.keys())
        # ax1f1.xaxis.set_major_locator(mdates.MonthLocator())  # Set major ticks to months
        # ax1f1.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d'))  # Format the date
        # ax1f1.set_xlabel('Date')
        # ax1f1.set_title('Bank Transactions')

        # Rotate date labels for better visibility
        # plt.setp(ax1f1.xaxis.get_majorticklabels(), rotation=45, ha='right')
        min_x, max_x = values['graf_range']
        # print('min_x, max_x', min_x, max_x)
        ax1f1.axvline(x=min_x, linewidth=2, color='k') #, label='Present'
        ax1f1.axvline(x=max_x, linewidth=2, color='k')#, label='sd'
        xticks.append(min_x)
        xticks.append(max_x)
        # labels.append(str(min_x))
        # labels.append(str(max_x))
        ax1f1.set_yticks([], [])
        # ax1f1.set_xticks(xticks, labels=labels)
        ax1f1.tick_params(axis='x', rotation=55)
        ax1f1.legend(loc='right')#, bbox_to_anchor=(-0.005, 0.5)
        # ax1f1.autoscale(enable=True)

        self.rm_time_plots(ui_loc_de_plot)
        self.add_time_plots(fig1, ui_loc_de_plot)

    def add_time_plots(self, fig, ui_loc_de_plot):
        # #print(sys._getframe().f_code.co_name)
        self.canvas_time_plots = FigureCanvas(fig)
        ui_loc_de_plot.addWidget(self.canvas_time_plots)

    def rm_time_plots(self, ui_loc_de_plot):
        # #print(sys._getframe().f_code.co_name)
        ui_loc_de_plot.removeWidget(self.canvas_time_plots)
        self.canvas_time_plots.close()

    # def prep_2Dplotplan_vs_real_bkp(self):
    #     print('Module: {}, Class: {}, Def: {}'.format(__name__, __class__, sys._getframe().f_code.co_name))
    #     year = int(self.ui.SB_year.value())
    #     conto = self.ui.cbActiveConto.currentText()
    #     payments_dict, labels = self.app_planned.prep_conto_yearly_graf(year)
    #     print('payments_dict----', payments_dict)
    #     sorted_payments_dict = dict(sorted(payments_dict.items(), key=lambda item: item[0]))
    #     real_payments_dict, labels = self.app_reale.prep_real_expenses_yearly_graf(year)
    #     sorted_real_payments_dict = dict(sorted(real_payments_dict.items(), key=lambda item: item[0]))
    #     real_income_dict, labels = self.app_reale.prep_real_income_yearly_graf(year)
    #     year_before = year - 1
    #     # year_before_payments_dict, labels = self.app_planned.prep_conto_yearly_graf(year_before)
    #     year_before_real_payments_dict, labels = self.app_reale.prep_real_expenses_yearly_graf(year_before)
    #     year_before_real_income_dict, labels = self.app_reale.prep_real_income_yearly_graf(year_before)
    #     fig1 = Figure()
    #     if conto == 'all':
    #         if not payments_dict:
    #             print('NO yearly table')
    #             return
    #         if self.ui.CBMonths.currentText() == 'month':
    #             spec5 = fig1.add_gridspec(ncols=1, nrows=1)#, height_ratios=[2, 1]
    #             ax1f2 = fig1.add_subplot()
    #         else:
    #             spec5 = fig1.add_gridspec(nrows=2, ncols=2, height_ratios=[1, 2])
    #             current_month = self.ui.CBMonths.currentText()
    #             indx_mnth = labels.index(current_month)
    #             ###############Total Real Expenses:########################
    #             ax1f1 = fig1.add_subplot(spec5[0, 1])  #
    #             total_monthly_values = real_payments_dict['all']
    #             # print('total_monthly_values***', total_monthly_values, type(total_monthly_values))
    #             total_monthly_value = total_monthly_values[indx_mnth]
    #             # print('total_monthly_value***', total_monthly_value)
    #             pielabels = []
    #             piesizes = []
    #             for myConto, yearly_list in sorted_real_payments_dict.items():
    #                 if myConto == 'all':
    #                     continue
    #                 # print('myContoreal_payments_dict, yearly_list, ', myConto, yearly_list, )
    #                 value = yearly_list[indx_mnth]
    #                 txt = '{} = {:.2f}'.format(myConto, value)
    #                 # txt = ''.format(myConto, value)
    #                 pielabels.append(txt)
    #                 size = (value / total_monthly_value) * 100
    #                 piesizes.append(size)
    #
    #             # ax1f1.grid(True)
    #             ax1f1.pie(piesizes, labels=pielabels,  startangle=90)#autopct='%1.2f%%',
    #             ax1f1.axis('equal')
    #             ax1f1.set_title('Total Real Expenses: {}'.format(total_monthly_values[indx_mnth]))
    #             ax1f1.legend()
    #
    #             ###############Total Planned Expenses:########################
    #             ax1r0c0 = fig1.add_subplot(spec5[0, 0])  #
    #             total_monthly_values = payments_dict['all']
    #             # print('total_monthly_values***', total_monthly_values, type(total_monthly_values))
    #             total_monthly_value = total_monthly_values[indx_mnth]
    #             # print('total_monthly_value***', total_monthly_value)
    #             pielabels = []
    #             piesizes = []
    #             for myConto, yearly_list in sorted_payments_dict.items():
    #                 if myConto == 'all':
    #                     continue
    #                 print('myConto::planned_payments_dict, yearly_list, ', myConto, yearly_list, )
    #                 value = yearly_list[indx_mnth]
    #                 if value is None:
    #                     value = 0
    #                 txt = '{} = {:.2f}'.format(myConto, value)
    #                 pielabels.append(txt)
    #                 size = (value / total_monthly_value) * 100
    #                 piesizes.append(size)
    #             ax1r0c0.pie(piesizes, labels=pielabels, startangle=90) #, autopct='%1.2f%%'
    #             ax1r0c0.axis('equal')
    #             ax1r0c0.set_title('Total Planned Expenses: {}'.format(total_monthly_values[indx_mnth]))
    #             ax1r0c0.legend()
    #
    #             ax1f2 = fig1.add_subplot(spec5[1, :])
    #         ax1f2.grid(True)
    #
    #         # Version 1##########################################################################
    #         # x = np.arange(len(labels))  # the label locations
    #         # bottom1 = np.zeros(len(labels))
    #         # bottom2 = np.zeros(len(labels))
    #         # width = 0.3  # the width of the bars: can also be len(x) sequence
    #         # for conto in payments_dict.keys():
    #         #     list_of_expenses = payments_dict[conto]
    #         #     p1 = ax1f2.bar(x - width / 2, list_of_expenses, width, label=conto, bottom=bottom1)
    #         #     ax1f2.bar_label(p1, label_type='center')
    #         #     bottom1 += list_of_expenses
    #         #     list_of_expenses = real_payments_dict[conto]
    #         #     p2 = ax1f2.bar(x + width / 2, list_of_expenses, width, label=conto, bottom=bottom2)
    #         #     ax1f2.bar_label(p2, label_type='center')
    #         #     bottom2 += list_of_expenses
    #
    #         # Version 2#########################################################################
    #         # x = np.arange(len(labels))  # the label locations
    #         # # bottom1 = np.zeros(len(labels))
    #         # width = 0.1  # the width of the bars: can also be len(x) sequence
    #         # for i, conto in enumerate(payments_dict.keys()):
    #         #     list_of_expenses = payments_dict[conto]
    #         #     sublabel = 'planned {}'.format(conto)
    #         #     p1 = ax1f2.bar(x+i/10, list_of_expenses, width, label=sublabel)#, bottom=bottom1
    #         #     ax1f2.bar_label(p1, label_type='center')
    #         #     # bottom1 += list_of_expenses
    #         #
    #         #     list_of_expenses = real_payments_dict[conto]
    #         #     sublabel = 'real {}'.format(conto)
    #         #     p2 = ax1f2.bar((x-1)+i/10, list_of_expenses, width, label=sublabel) #, bottom=bottom2
    #         #     ax1f2.bar_label(p2, label_type='center')
    #         #     # bottom2 += list_of_expenses
    #
    #         #Version 3#########################################################################
    #         x = np.arange(len(labels))  # the label locations
    #         # bottom1 = np.zeros(len(labels))
    #         width = 0.25  # the width of the bars: can also be len(x) sequence
    #         # for i, conto in enumerate(payments_dict.keys()):
    #         list_of_expenses = payments_dict[conto]
    #         sublabel = 'planned expenses {}'.format(conto)
    #         # print('x-width, list_of_expenses', x-width, list_of_expenses)
    #         p1 = ax1f2.bar(x, list_of_expenses, width, label=sublabel)#, bottom=bottom1
    #         ax1f2.bar_label(p1, label_type='center', rotation=90)
    #         # bottom1 += list_of_expenses
    #         if real_payments_dict and conto in list(real_payments_dict.keys()):
    #             list_of_expenses = real_payments_dict[conto]
    #             sublabel = 'real expenses {}'.format(conto)
    #             # print('x, list_of_expenses', x, list_of_expenses)
    #             p2 = ax1f2.bar(x+width, list_of_expenses, width, label=sublabel) #, bottom=bottom2
    #             ax1f2.bar_label(p2, label_type='center', rotation=90)
    #         if real_income_dict and conto in list(real_income_dict.keys()):
    #             list_of_expenses = real_income_dict[conto]
    #             sublabel = 'real income {}'.format(conto)
    #             # print('x, list_of_expenses', x, list_of_expenses)
    #             p2 = ax1f2.bar(x+width, list_of_expenses, width, label=sublabel) #, bottom=bottom2
    #             ax1f2.bar_label(p2, label_type='center', rotation=90)
    #         # if year_before_payments_dict:
    #         #     list_of_expenses = year_before_payments_dict[conto]
    #         #     sublabel = 'planned expenses {} {}'.format(year_before, conto)
    #         #     # print('x, list_of_expenses', x, list_of_expenses)
    #         #     p2 = ax1f2.bar(x, list_of_expenses, width, label=sublabel) #, bottom=bottom2
    #         #     ax1f2.bar_label(p2, label_type='center', rotation=90)
    #         if year_before_real_payments_dict:
    #             list_of_expenses = year_before_real_payments_dict[conto]
    #             sublabel = 'real expenses {} {}'.format(year_before, conto)
    #             # print('x, list_of_expenses', x, list_of_expenses)
    #             p2 = ax1f2.bar(x-width, list_of_expenses, width, label=sublabel) #, bottom=bottom2
    #             ax1f2.bar_label(p2, label_type='center', rotation=90)
    #         if year_before_real_income_dict:
    #             list_of_expenses = year_before_real_income_dict[conto]
    #             sublabel = 'real income {} {}'.format(year_before, conto)
    #             # print('x, list_of_expenses', x, list_of_expenses)
    #             p2 = ax1f2.bar(x-width, list_of_expenses, width, label=sublabel) #, bottom=bottom2
    #             ax1f2.bar_label(p2, label_type='center', rotation=90)
    #         ax1f2.set_xticks(x)
    #         ax1f2.set_xticklabels(labels)
    #         ax1f2.tick_params(axis='x', rotation=55)
    #         ax1f2.legend()
    #     else:
    #         # self.ui.GB_planvsReal_table.setVisible(False)
    #         spec5 = fig1.add_gridspec(nrows=2, ncols=2, height_ratios=[1, 1])
    #
    #         # current_month = self.ui.CBMonths.currentText()
    #         # indx_mnth = labels.index(current_month)
    #
    #         ###############Total Real Expenses:########################
    #         # ax1f1 = fig1.add_subplot(spec5[0, 1])  #
    #         # total_monthly_values = real_payments_dict['all']
    #         # # print('total_monthly_values***', total_monthly_values, type(total_monthly_values))
    #         # total_monthly_value = total_monthly_values[indx_mnth]
    #         # # print('total_monthly_value***', total_monthly_value)
    #         # pielabels = []
    #         # piesizes = []
    #         # for myConto, yearly_list in sorted_real_payments_dict.items():
    #         #     if myConto == 'all':
    #         #         continue
    #         #     print('myContoreal_payments_dict, yearly_list, ', myConto, yearly_list, )
    #         #     value = yearly_list[indx_mnth]
    #         #     txt = '{} = {:.2f}'.format(myConto, value)
    #         #     # txt = ''.format(myConto, value)
    #         #     pielabels.append(txt)
    #         #     size = (value / total_monthly_value) * 100
    #         #     piesizes.append(size)
    #         #
    #         # # ax1f1.grid(True)
    #         # ax1f1.pie(piesizes, labels=pielabels, startangle=90)  # autopct='%1.2f%%',
    #         # ax1f1.axis('equal')
    #         # ax1f1.set_title('Total Real Expenses: {}'.format(total_monthly_values[indx_mnth]))
    #         # ax1f1.legend()
    #
    #         ###############Total Planned Expenses:########################
    #         # ax1r0c0 = fig1.add_subplot(spec5[0, 0])  #
    #         # total_monthly_values = payments_dict['all']
    #         # # print('total_monthly_values***', total_monthly_values, type(total_monthly_values))
    #         # total_monthly_value = total_monthly_values[indx_mnth]
    #         # # print('total_monthly_value***', total_monthly_value)
    #         # pielabels = []
    #         # piesizes = []
    #         # for myConto, yearly_list in sorted_payments_dict.items():
    #         #     if myConto == 'all':
    #         #         continue
    #         #     print('myConto::planned_payments_dict, yearly_list, ', myConto, yearly_list, )
    #         #     value = yearly_list[indx_mnth]
    #         #     txt = '{} = {:.2f}'.format(myConto, value)
    #         #     pielabels.append(txt)
    #         #     size = (value / total_monthly_value) * 100
    #         #     piesizes.append(size)
    #         # ax1r0c0.pie(piesizes, labels=pielabels, startangle=90)  # , autopct='%1.2f%%'
    #         # ax1r0c0.axis('equal')
    #         # ax1r0c0.set_title('Total Planned Expenses: {}'.format(total_monthly_values[indx_mnth]))
    #         # ax1r0c0.legend()
    #
    #         fig1
    #         ###############Planned Category########################
    #         try:
    #             ax1f1 = fig1.add_subplot(spec5[0, 0])  #
    #             piesizes, pielabels, total_monthly_values = self.app_planned.category_values4pie()
    #             # ax1f1.grid(True)
    #             ax1f1.pie(piesizes, labels=pielabels, startangle=90)  # autopct='%1.2f%%',
    #             ax1f1.axis('equal')
    #             ax1f1.set_title('Category Planned Expenses: {}'.format(total_monthly_values))
    #             ax1f1.legend()
    #         except:
    #             print(traceback.format_exc())
    #         ###############Real Category########################
    #         try:
    #             ax1f1 = fig1.add_subplot(spec5[0, 1])  #
    #             piesizes, pielabels, total_monthly_values = self.app_reale.category_values4pie()
    #             # ax1f1.grid(True)
    #             ax1f1.pie(piesizes, labels=pielabels, startangle=90)  # autopct='%1.2f%%',
    #             ax1f1.axis('equal')
    #             ax1f1.set_title('Real Category Expenses: {}'.format(total_monthly_values))
    #             ax1f1.legend()
    #         except:
    #             print(traceback.format_exc())
    #         ############### Name Planned########################
    #         try:
    #             ax1f1 = fig1.add_subplot(spec5[1, 0])  #
    #             piesizes, pielabels, total_monthly_values = self.app_planned.name_values4pie()
    #             # ax1f1.grid(True)
    #             ax1f1.pie(piesizes, labels=pielabels, startangle=90)  # autopct='%1.2f%%',
    #             ax1f1.axis('equal')
    #             ax1f1.set_title('All Planned Expenses: {}'.format(total_monthly_values))
    #             ax1f1.legend()
    #         except:
    #             print(traceback.format_exc())
    #
    #         ############### Name Real ########################
    #         try:
    #             ax1f1 = fig1.add_subplot(spec5[1, 1])  #
    #             piesizes, pielabels, total_monthly_values = self.app_reale.names_values4pie()
    #             # ax1f1.grid(True)
    #             ax1f1.pie(piesizes, labels=pielabels, startangle=90)  # autopct='%1.2f%%',
    #             ax1f1.axis('equal')
    #             ax1f1.set_title('All Real Planned Expenses: {}'.format(total_monthly_values))
    #             ax1f1.legend()
    #         except:
    #             print(traceback.format_exc())
    #
    #     self.rmmplplan_vs_real()
    #     self.add_plotsplan_vs_real(fig1)

    def prep_2Dplotplan_vs_real(self):
        print('Module: {}, Class: {}, Def: {}'.format(__name__, __class__, sys._getframe().f_code.co_name))
        plot_version = 1
        year = int(self.ui.SB_year.value())
        conto = self.ui.cbActiveConto.currentText()
        labels = self.app_online.all_year_months
        fig1 = Figure()

        pieplot = False
        if self.ui.CBMonths.currentText() == 'month':
            spec5 = fig1.add_gridspec(ncols=1, nrows=1)#, height_ratios=[2, 1]
            ax1f2 = fig1.add_subplot()
            label_locations = np.arange(len(labels))  # the label locations
            width = 0.25  # the width of the bars: can also be len(x) sequence
            if self.app_online.planned_expenses_per_conto_per_month and conto in list(
                    self.app_online.planned_expenses_per_conto_per_month.keys()):
                if plot_version == 1:
                    list_of_expenses = self.app_online.planned_expenses_per_conto_per_month[conto]
                    sublabel = 'planned expenses {}'.format(conto)
                    p1 = ax1f2.bar(label_locations, list_of_expenses, width, label=sublabel)  # , bottom=bottom1
                    ax1f2.bar_label(p1, label_type='center', rotation=90)
                    ax1f2.axhline(y=self.app_online.planned_expenses_average['all'], linewidth=2, color='k',
                                  label='yearly_average_planned')
                elif plot_version == 2:
                    bottom1 = np.zeros(len(labels))
                    for conto in self.app_online.planned_expenses_per_conto_per_month.keys():
                        list_of_expenses = self.app_online.planned_expenses_per_conto_per_month[conto]
                        list_of_expenses = [0 if v is None else v for v in list_of_expenses]
                        p1 = ax1f2.bar(label_locations - width / 2, list_of_expenses, width, label=conto,
                                       bottom=bottom1)
                        ax1f2.bar_label(p1, label_type='center')
                        bottom1 += list_of_expenses
                elif plot_version == 3:
                    width = 0.1
                    for i, conto in enumerate(self.app_online.planned_expenses_per_conto_per_month.keys()):
                        list_of_expenses = self.app_online.planned_expenses_per_conto_per_month[conto]
                        list_of_expenses = [0 if v is None else v for v in list_of_expenses]
                        sublabel = 'planned {}'.format(conto)
                        p1 = ax1f2.bar(label_locations + i / 10, list_of_expenses, width,
                                       label=sublabel)  # , bottom=bottom1
                        ax1f2.bar_label(p1, label_type='center')
            if self.app_online.planned_income_per_conto_per_month and conto in list(
                    self.app_online.planned_income_per_conto_per_month.keys()):
                if plot_version == 1:
                    list_of_expenses = self.app_online.planned_income_per_conto_per_month[conto]
                    sublabel = 'planned income {}'.format(conto)
                    p1 = ax1f2.bar(label_locations, list_of_expenses, width, label=sublabel)  # , bottom=bottom1
                    ax1f2.bar_label(p1, label_type='center', rotation=90)
                    # ax1f2.axhline(y=self.app_online.planned_expenses_average['all'], linewidth=2, color='k', label='yearly_average_planned')
                elif plot_version == 2:
                    bottom1 = np.zeros(len(labels))
                    for conto in self.app_online.planned_income_per_conto_per_month.keys():
                        list_of_expenses = self.app_online.planned_income_per_conto_per_month[conto]
                        list_of_expenses = [0 if v is None else v for v in list_of_expenses]
                        p1 = ax1f2.bar(label_locations - width / 2, list_of_expenses, width, label=conto,
                                       bottom=bottom1)
                        ax1f2.bar_label(p1, label_type='center')
                        bottom1 += list_of_expenses
                elif plot_version == 3:
                    width = 0.1
                    for i, conto in enumerate(self.app_online.planned_income_per_conto_per_month.keys()):
                        list_of_expenses = self.app_online.planned_income_per_conto_per_month[conto]
                        list_of_expenses = [0 if v is None else v for v in list_of_expenses]
                        sublabel = 'planned {}'.format(conto)
                        p1 = ax1f2.bar(label_locations + i / 10, list_of_expenses, width,
                                       label=sublabel)  # , bottom=bottom1
                        ax1f2.bar_label(p1, label_type='center')
            if self.app_online.real_expenses_per_conto_per_month and conto in list(
                    self.app_online.real_expenses_per_conto_per_month.keys()):
                list_of_expenses = self.app_online.real_expenses_per_conto_per_month[conto]
                sublabel = 'real expenses {}'.format(conto)
                # print('x, list_of_expenses', x, list_of_expenses)
                p2 = ax1f2.bar(label_locations + width, list_of_expenses, width, label=sublabel)  # , bottom=bottom2
                ax1f2.bar_label(p2, label_type='center', rotation=90)
                ax1f2.axhline(y=self.app_online.real_expenses_average['all'], linewidth=2, color='k',
                              label='real_expenses_average')
            if self.app_online.real_income_per_conto_per_month and conto in list(
                    self.app_online.real_income_per_conto_per_month.keys()):
                list_of_expenses = self.app_online.real_income_per_conto_per_month[conto]
                sublabel = 'real income {}'.format(conto)
                # print('x, list_of_expenses', x, list_of_expenses)
                p2 = ax1f2.bar(label_locations + width, list_of_expenses, width, label=sublabel)  # , bottom=bottom2
                ax1f2.bar_label(p2, label_type='center', rotation=90)
            ax1f2.set_xticks(label_locations)
            ax1f2.set_xticklabels(labels)
            ax1f2.tick_params(axis='x', rotation=55)
            ax1f2.legend()
            ax1f2.grid(True)
            year_before = year - 1
            self.app_online.year = year_before
            self.app_online.prepareTablePlan()
            year_before_real_payments_dict = self.app_online.real_expenses_per_conto_per_month
            year_before_real_income_dict = self.app_online.real_income_per_conto_per_month
            if year_before_real_payments_dict:
                list_of_expenses = year_before_real_payments_dict[conto]
                sublabel = 'real expenses {} {}'.format(year_before, conto)
                # print('x, list_of_expenses', x, list_of_expenses)
                p2 = ax1f2.bar(label_locations-width, list_of_expenses, width, label=sublabel) #, bottom=bottom2
                ax1f2.bar_label(p2, label_type='center', rotation=90)
            if year_before_real_income_dict:
                list_of_expenses = year_before_real_income_dict[conto]
                sublabel = 'real income {} {}'.format(year_before, conto)
                # print('x, list_of_expenses', x, list_of_expenses)
                p2 = ax1f2.bar(label_locations-width, list_of_expenses, width, label=sublabel) #, bottom=bottom2
                ax1f2.bar_label(p2, label_type='center', rotation=90)
        else:
            pieplot = True
            if self.ui.RB_plot_conto.isChecked():
                row1 = (self.app_online.planned_expenses_per_conto_per_month, self.app_online.real_expenses_per_conto_per_month)
                row2 = (self.app_online.planned_income_per_conto_per_month, self.app_online.real_income_per_conto_per_month)
            elif self.ui.RB_plot_category.isChecked():
                row1 = (self.app_online.planned_expenses_per_category_per_month, self.app_online.real_expenses_per_category_per_month)
                row2 = (self.app_online.planned_income_per_category_per_month, self.app_online.real_income_per_category_per_month)

            year_before = year - 1
            self.app_online.year = year_before
            self.app_online.prepareTablePlan()
            if self.ui.RB_plot_conto.isChecked():
                row3 = (self.app_online.planned_expenses_per_conto_per_month, self.app_online.real_expenses_per_conto_per_month)
            elif self.ui.RB_plot_category.isChecked():
                row3 = (self.app_online.planned_expenses_per_category_per_month, self.app_online.real_expenses_per_category_per_month)

            arr = [row1, row2, row3]
            arr = np.atleast_2d(arr)
            spec5 = fig1.add_gridspec(nrows=arr.shape[0], ncols=arr.shape[1]) #, height_ratios=[1, 2]
            # ax1f2 = fig1.add_subplot(spec5[1, :])

            for row in range(arr.shape[0]):
                if row == 0:
                    exp_inc = 'expenses'
                elif row == 1:
                    exp_inc = 'income'
                elif row == 2:
                    exp_inc = 'expenses {}'.format(year-1)
                # new_planned_expenses_per_category_per_month, \
                # new_real_expenses_per_category_per_month = self.app_online.get_common_categories(arr[row, 0], arr[row, 1])
                results = self.app_online.get_common_categories(arr[row, 0], arr[row, 1])
                for col in range(arr.shape[1]):
                    if col == 0:
                        pln_rl = 'planned'
                    elif col == 1:
                        pln_rl = 'real'
                    res = results[col]
                    axaxax = fig1.add_subplot(spec5[row, col])
                    total_monthly_value = res['all']
                    pielabels = []
                    piesizes = []
                    for myConto, yearly_list in res.items():
                        if myConto == 'all':
                            continue
                        value = yearly_list
                        if value is None:
                            value = 0
                        txt = '{} = {:.2f}'.format(myConto, value)
                        pielabels.append(txt)
                        size = (value / total_monthly_value) * 100
                        piesizes.append(size)
                    axaxax.pie(piesizes, labels=pielabels, startangle=90)  # , autopct='%1.2f%%'
                    axaxax.axis('equal')
                    axaxax.set_title('Total {} {}: {}'.format(pln_rl, exp_inc, total_monthly_value))
                    axaxax.legend()

            # ###############Total Planned Expenses:########################
            # ax1r0c0 = fig1.add_subplot(spec5[0, 0])
            # if self.ui.RB_plot_conto.isChecked():
            #     new_planned_expenses_per_category_per_month, \
            #     new_real_expenses_per_category_per_month = self.app_online.get_common_categories(
            #         self.app_online.planned_expenses_per_conto_per_month, self.app_online.real_expenses_per_conto_per_month)
            # elif self.ui.RB_plot_category.isChecked():
            #     new_planned_expenses_per_category_per_month, \
            #     new_real_expenses_per_category_per_month = self.app_online.get_common_categories(
            #         self.app_online.planned_expenses_per_category_per_month, self.app_online.real_expenses_per_category_per_month)
            #
            # total_monthly_value = new_planned_expenses_per_category_per_month['all']
            # pielabels = []
            # piesizes = []
            # for myConto, yearly_list in new_planned_expenses_per_category_per_month.items():
            #     if myConto == 'all':
            #         continue
            #     value = yearly_list
            #     if value is None:
            #         value = 0
            #     txt = '{} = {:.2f}'.format(myConto, value)
            #     pielabels.append(txt)
            #     size = (value / total_monthly_value) * 100
            #     piesizes.append(size)
            # ax1r0c0.pie(piesizes, labels=pielabels, startangle=90) #, autopct='%1.2f%%'
            # ax1r0c0.axis('equal')
            # ax1r0c0.set_title('Total Planned Expenses: {}'.format(total_monthly_value))
            # ax1r0c0.legend()
            # ###############Total Real Expenses:########################
            # ax1f1 = fig1.add_subplot(spec5[0, 1])  #
            # total_monthly_value = new_real_expenses_per_category_per_month['all']
            # pielabels = []
            # piesizes = []
            # for myConto, yearly_list in new_real_expenses_per_category_per_month.items():
            #     if myConto == 'all':
            #         continue
            #     value = yearly_list
            #     txt = '{} = {:.2f}'.format(myConto, value)
            #     pielabels.append(txt)
            #     size = (value / total_monthly_value) * 100
            #     piesizes.append(size)
            # # ax1f1.grid(True)
            # ax1f1.pie(piesizes, labels=pielabels,  startangle=90)#autopct='%1.2f%%',
            # ax1f1.axis('equal')
            # ax1f1.set_title('Total Real Expenses: {}'.format(total_monthly_value))
            # ax1f1.legend()

        # else:
        #     # self.ui.GB_planvsReal_table.setVisible(False)
        #     spec5 = fig1.add_gridspec(nrows=2, ncols=2, height_ratios=[1, 1])
        #
        #     # current_month = self.ui.CBMonths.currentText()
        #     # indx_mnth = labels.index(current_month)
        #
        #     ###############Total Real Expenses:########################
        #     # ax1f1 = fig1.add_subplot(spec5[0, 1])  #
        #     # total_monthly_values = real_payments_dict['all']
        #     # # print('total_monthly_values***', total_monthly_values, type(total_monthly_values))
        #     # total_monthly_value = total_monthly_values[indx_mnth]
        #     # # print('total_monthly_value***', total_monthly_value)
        #     # pielabels = []
        #     # piesizes = []
        #     # for myConto, yearly_list in sorted_real_payments_dict.items():
        #     #     if myConto == 'all':
        #     #         continue
        #     #     print('myContoreal_payments_dict, yearly_list, ', myConto, yearly_list, )
        #     #     value = yearly_list[indx_mnth]
        #     #     txt = '{} = {:.2f}'.format(myConto, value)
        #     #     # txt = ''.format(myConto, value)
        #     #     pielabels.append(txt)
        #     #     size = (value / total_monthly_value) * 100
        #     #     piesizes.append(size)
        #     #
        #     # # ax1f1.grid(True)
        #     # ax1f1.pie(piesizes, labels=pielabels, startangle=90)  # autopct='%1.2f%%',
        #     # ax1f1.axis('equal')
        #     # ax1f1.set_title('Total Real Expenses: {}'.format(total_monthly_values[indx_mnth]))
        #     # ax1f1.legend()
        #
        #     ###############Total Planned Expenses:########################
        #     # ax1r0c0 = fig1.add_subplot(spec5[0, 0])  #
        #     # total_monthly_values = payments_dict['all']
        #     # # print('total_monthly_values***', total_monthly_values, type(total_monthly_values))
        #     # total_monthly_value = total_monthly_values[indx_mnth]
        #     # # print('total_monthly_value***', total_monthly_value)
        #     # pielabels = []
        #     # piesizes = []
        #     # for myConto, yearly_list in sorted_payments_dict.items():
        #     #     if myConto == 'all':
        #     #         continue
        #     #     print('myConto::planned_payments_dict, yearly_list, ', myConto, yearly_list, )
        #     #     value = yearly_list[indx_mnth]
        #     #     txt = '{} = {:.2f}'.format(myConto, value)
        #     #     pielabels.append(txt)
        #     #     size = (value / total_monthly_value) * 100
        #     #     piesizes.append(size)
        #     # ax1r0c0.pie(piesizes, labels=pielabels, startangle=90)  # , autopct='%1.2f%%'
        #     # ax1r0c0.axis('equal')
        #     # ax1r0c0.set_title('Total Planned Expenses: {}'.format(total_monthly_values[indx_mnth]))
        #     # ax1r0c0.legend()
        #
        #     fig1
        #     ###############Planned Category########################
        #     try:
        #         ax1f1 = fig1.add_subplot(spec5[0, 0])  #
        #         piesizes, pielabels, total_monthly_values = self.app_planned.category_values4pie()
        #         # ax1f1.grid(True)
        #         ax1f1.pie(piesizes, labels=pielabels, startangle=90)  # autopct='%1.2f%%',
        #         ax1f1.axis('equal')
        #         ax1f1.set_title('Category Planned Expenses: {}'.format(total_monthly_values))
        #         ax1f1.legend()
        #     except:
        #         print(traceback.format_exc())
        #     ###############Real Category########################
        #     try:
        #         ax1f1 = fig1.add_subplot(spec5[0, 1])  #
        #         piesizes, pielabels, total_monthly_values = self.app_reale.category_values4pie()
        #         # ax1f1.grid(True)
        #         ax1f1.pie(piesizes, labels=pielabels, startangle=90)  # autopct='%1.2f%%',
        #         ax1f1.axis('equal')
        #         ax1f1.set_title('Real Category Expenses: {}'.format(total_monthly_values))
        #         ax1f1.legend()
        #     except:
        #         print(traceback.format_exc())
        #     ############### Name Planned########################
        #     try:
        #         ax1f1 = fig1.add_subplot(spec5[1, 0])  #
        #         piesizes, pielabels, total_monthly_values = self.app_planned.name_values4pie()
        #         # ax1f1.grid(True)
        #         ax1f1.pie(piesizes, labels=pielabels, startangle=90)  # autopct='%1.2f%%',
        #         ax1f1.axis('equal')
        #         ax1f1.set_title('All Planned Expenses: {}'.format(total_monthly_values))
        #         ax1f1.legend()
        #     except:
        #         print(traceback.format_exc())
        #
        #     ############### Name Real ########################
        #     try:
        #         ax1f1 = fig1.add_subplot(spec5[1, 1])  #
        #         piesizes, pielabels, total_monthly_values = self.app_reale.names_values4pie()
        #         # ax1f1.grid(True)
        #         ax1f1.pie(piesizes, labels=pielabels, startangle=90)  # autopct='%1.2f%%',
        #         ax1f1.axis('equal')
        #         ax1f1.set_title('All Real Planned Expenses: {}'.format(total_monthly_values))
        #         ax1f1.legend()
        #     except:
        #         print(traceback.format_exc())

        self.rmmplplan_vs_real()
        self.add_plotsplan_vs_real(fig1)

    def add_plotsplan_vs_real(self, fig):
        # print('Module: {}, Class: {}, Def: {}'.format(__name__, __class__, sys._getframe().f_code.co_name))
        self.canvasplan_vs_real = FigureCanvas(fig)
        self.ui.loc_de_plot_PlanVsReal.addWidget(self.canvasplan_vs_real)

    def rmmplplan_vs_real(self):
        # print('Module: {}, Class: {}, Def: {}'.format(__name__, __class__, sys._getframe().f_code.co_name))
        self.ui.loc_de_plot_PlanVsReal.removeWidget(self.canvasplan_vs_real)
        self.canvasplan_vs_real.close()

    def contextMenu_verticalrealTable(self, event):
        contextMenu = QMenu(self)
        item = self.ui.realTable.itemAt(event)
        if item is not None:
            contextMenu.addAction("show in bank table")
            contextMenu.addAction("delete from plan_vs_real and id from_bank_table")
        action = contextMenu.exec_(self.ui.planTable.mapToGlobal(event))

        if action is not None:
            if action.text() == "show in bank table":
                if not self.ui.CBOrigTableHead.isChecked():
                    message = 'please check the original SQL table head'
                    QMessageBox.warning(self, 'Inconsistent Data', message, QMessageBox.Ok)
                    return
                selectedRowsIndexes = self.ui.realTable.selectionModel().selectedRows()
                if len(selectedRowsIndexes) > 1:
                    message = 'please select only one row'
                    QMessageBox.warning(self, 'Inconsistent Data', message, QMessageBox.Ok)
                    return

                print('ÖÖÖÖÖselectedRowsIndexes', selectedRowsIndexes, type(selectedRowsIndexes))
                row = selectedRowsIndexes[0]
                # for tt in selectedRowsIndexes:
                #     print(tt, type(tt))
                #     print(tt.row(), tt.column())
                #     cell = self.ui.realTable.item(tt.row(), 0)
                #     print('cell.text()', cell.text())
                id = self.ui.realTable.item(row.row(), 0).text()
                category = self.ui.realTable.item(row.row(), 4).text()
                myconto = self.ui.realTable.item(row.row(), 5).text()
                id_bank_table = self.ui.realTable.item(row.row(), 9).text()

                if category == 'None':
                    rel_id = id
                else:
                    rel_id = id_bank_table
                # print('category#####myconto', category, myconto)
                # print('category#####myconto', type(category), type(myconto))
                # if category == 'None':
                self.ui.cbActiveConto.setCurrentText(myconto)
                filter_txt = 'id="{}"'.format(id)
                self.ui.lineEditFilterList.setText(filter_txt)
                self.ui.TW_main_user_interface.setCurrentIndex(4)
                bank = self.app_reale.get_bank(myconto)
                if bank == 'Stadtsparkasse München':
                    sql_table = self.app_reale.sskm
                elif bank == 'DeutscheBank':
                    sql_table = self.app_reale.deubnk
                elif bank == 'N26':
                    sql_table = self.app_reale.n26
                self.applyFilter(colName='id', filter=rel_id, qt_table=self.ui.TWsskm, sql_table=sql_table)
            if action.text() == "delete from plan_vs_real and id from_bank_table":
                if not self.ui.CBOrigTableHead.isChecked():
                    message = 'please check the original SQL table head'
                    QMessageBox.warning(self, 'Inconsistent Data', message, QMessageBox.Ok)
                    return
                selectedRowsIndexes = self.ui.realTable.selectionModel().selectedRows()
                ids_plan_vs_real = []
                for row in selectedRowsIndexes:
                    id = self.ui.realTable.item(row.row(), 0).text()
                    ids_plan_vs_real.append(id)
                self.app_reale.delete_from_plan_vs_real_and_id_from_bank_table(ids_plan_vs_real=ids_plan_vs_real)

    def contextMenu_verticalrealTableIncome(self, event):
        contextMenu = QMenu(self)
        item = self.ui.realTableIncome.itemAt(event)
        if item is not None:
            contextMenu.addAction("show in bank table")
        action = contextMenu.exec_(self.ui.realTableIncome.mapToGlobal(event))

        if action is not None:
            if action.text() == "show in bank table":
                if not self.ui.CBOrigTableHead.isChecked():
                    message = 'please check the original SQL table head'
                    QMessageBox.warning(self, 'Inconsistent Data', message, QMessageBox.Ok)
                    return
                selectedRowsIndexes = self.ui.realTableIncome.selectionModel().selectedRows()
                if len(selectedRowsIndexes) > 1:
                    message = 'please select only one row'
                    QMessageBox.warning(self, 'Inconsistent Data', message, QMessageBox.Ok)
                    return

                print('ÖÖÖÖÖselectedRowsIndexes', selectedRowsIndexes, type(selectedRowsIndexes))
                row = selectedRowsIndexes[0]
                # for tt in selectedRowsIndexes:
                #     print(tt, type(tt))
                #     print(tt.row(), tt.column())
                #     cell = self.ui.realTable.item(tt.row(), 0)
                #     print('cell.text()', cell.text())
                id = self.ui.realTableIncome.item(row.row(), 0).text()
                category = self.ui.realTableIncome.item(row.row(), 4).text()
                myconto = self.ui.realTableIncome.item(row.row(), 5).text()
                id_bank_table = self.ui.realTableIncome.item(row.row(), 9).text()

                if category == 'None':
                    rel_id = id
                else:
                    rel_id = id_bank_table
                # print('category#####myconto', category, myconto)
                # print('category#####myconto', type(category), type(myconto))
                # if category == 'None':
                self.ui.cbActiveConto.setCurrentText(myconto)
                filter_txt = 'id="{}"'.format(id)
                self.ui.lineEditFilterList.setText(filter_txt)
                self.ui.TW_main_user_interface.setCurrentIndex(4)
                bank = self.app_reale.get_bank(myconto)
                if bank == 'Stadtsparkasse München':
                    sql_table = self.app_reale.sskm
                elif bank == 'DeutscheBank':
                    sql_table = self.app_reale.deubnk
                elif bank == 'N26':
                    sql_table = self.app_reale.n26
                self.applyFilter(colName='id', filter=rel_id, qt_table=self.ui.TWsskm, sql_table=sql_table)

    def contextMenu_plot_cols_from_table(self, event):
        # #print(sys._getframe().f_code.co_name)
        # #print('self.sender()', self.sender().parent())
        # #print('self.sender()', self.sender().parent().objectName())
        qtablewidget = self.sender().parent()
        contextMenu = QMenu(self)
        item = qtablewidget.itemAt(event)
        if item is not None:
            contextMenu.addAction("plot pie")
        action = contextMenu.exec_(qtablewidget.mapToGlobal(event))

        if action is not None:
            if action.text() == "plot pie":
                selectedColsIndexes = qtablewidget.selectionModel().selectedColumns()
                cols = []
                for tt in selectedColsIndexes:
                    # #print(tt, type(tt))
                    # #print(tt.row(), tt.column())
                    col_name = qtablewidget.horizontalHeaderItem(tt.column()).text()
                    cols.append(col_name)
                #print(cols)
                self.plotPie_new(cols, qtablewidget)

    def contextMenu_TWsskm(self, event):
        # #print(sys._getframe().f_code.co_name)
        # #print('self.sender()', self.sender().parent())
        # #print('self.sender()', self.sender().parent().objectName())
        qtablewidget = self.sender().parent()
        contextMenu = QMenu(self)
        item = qtablewidget.itemAt(event)
        if item is not None:
            contextMenu.addAction("add to chelt_plan")
            contextMenu.addAction("add to knowntrans")
        action = contextMenu.exec_(qtablewidget.mapToGlobal(event))

        currentConto = self.ui.cbActiveConto.currentText()
        bank = self.app_reale.get_bank(currentConto)
        if bank == 'Stadtsparkasse München':
            sql_table = self.app_reale.sskm
        elif bank == 'DeutscheBank':
            sql_table = self.app_reale.deubnk
        elif bank == 'N26':
            sql_table = self.app_reale.n26

        if action is not None:
            selectedRowsIndexes = self.ui.TWsskm.selectionModel().selectedRows()
            idrow = self.ui.TWsskm.item(selectedRowsIndexes[0].row(), 0).text()
            if action.text() == "add to knowntrans":
                identif_cols_name_category = AddRowWindow.get_identification_cols_for_knowntrans(self.user.id, sql_table)
                if identif_cols_name_category:
                    self.app_reale.add_row_to_knowntrans(currentConto, idrow, identif_cols_name_category)
            if action.text() == "add to chelt_plan":
                identif_cols_name_category = AddRowWindow.get_identification_cols_for_chelt_plan(self.user.id, sql_table)
                if identif_cols_name_category:
                    self.app_reale.add_row_to_chelt_plan(currentConto, idrow, identif_cols_name_category)

    def read_table(self, qtablewidget):
        # #print('Module: {}, Class: {}, Def: {}'.format(__name__, __class__, sys._getframe().f_code.co_name))
        rows = qtablewidget.rowCount()
        cols = qtablewidget.columnCount()
        planExpenseTable = np.empty((rows, cols), dtype=object)
        planExpenseTableHead = []
        for row in range(rows):
            for column in range(cols):
                cell = qtablewidget.item(row, column)
                planExpenseTable[row, column] = cell.text()
                colName = qtablewidget.horizontalHeaderItem(column).text()
                if colName not in planExpenseTableHead:
                    planExpenseTableHead.append(colName)

        return planExpenseTable, planExpenseTableHead

    def plotPie_new(self, cols, qtablewidget):
        #print('Module: {}, Class: {}, Def: {}'.format(__name__, __class__, sys._getframe().f_code.co_name))
        realExpenseTable, realExpenseTableHead = self.read_table(qtablewidget)
        # return
        try:
            allValues = realExpenseTable[:, realExpenseTableHead.index(cols[0])].astype(float)
            if None in allValues:
                allValues = allValues[allValues != np.array(None)]
            totalVal = sum(allValues)
            values_col = cols[0]
            names_col = cols[1]
        except:
            allValues = realExpenseTable[:, realExpenseTableHead.index(cols[1])].astype(float)
            if None in allValues:
                allValues = allValues[allValues != np.array(None)]
            totalVal = sum(allValues)
            values_col = cols[1]
            names_col = cols[0]

        colTableName = realExpenseTable[:, realExpenseTableHead.index(names_col)]
        labels = []
        sizes = []
        for table in np.unique(colTableName):
            indx = np.where(realExpenseTable[:, realExpenseTableHead.index(names_col)] == table)
            smallArray = realExpenseTable[indx]
            values = sum(smallArray[:, realExpenseTableHead.index(values_col)].astype(float))
            txt = '{} = {:.2f}'.format(table, values)
            labels.append(txt)
            size = (values / totalVal) * 100
            sizes.append(size)

        fig1, ax1 = plt.subplots()
        ax1.pie(sizes, labels=labels, autopct='%1.2f%%', startangle=90)
        ax1.axis('equal')
        plt.legend(title='Total: {:.2f}'.format(totalVal))

        plt.show()

    def add_transaction(self):
        res = AddRowWindow.add_transactions(self.user.id, self.chelt_db_connection.chelt_plan)
        if res:
            category, name, value, myconto, freq, pay_day, valid_from, valid_to, auto_ext, identification, cancel_auto_ext = res
            self.app_planned.add_transactions(category, name, value, myconto, freq, pay_day, valid_from,
                                              valid_to, auto_ext, identification, cancel_auto_ext,
                                              self.user.id)

    def add_conto(self):
        res = AddRowWindow.add_conto(self.user.id, self.chelt_db_connection.myAccountsTable)
        if res:
            name, banca = res
            self.app_reale.add_conto(self.user.id, name, banca)

    # def applyFilter_old(self, colName, filter):
    #     #print(sys._getframe().f_code.co_name)
    #     if filter == '':
    #         return
    #
    #     if self.defaultFilter:
    #         self.ui.lineEditFilterList.clear()
    #         self.defaultFilter = False
    #
    #     filterText = self.ui.lineEditFilterList.text()
    #     if not filterText:
    #         if isinstance(filter, str):
    #             filterText += '{}="{}"'.format(colName, filter)
    #         elif isinstance(filter, tuple):
    #             filterText += '{} < {} < {}'.format(filter[0], colName, filter[1])
    #         elif isinstance(filter, list):
    #             filterText += '{} in {}"'.format(str(filter), colName)
    #     else:
    #         if isinstance(filter, str):
    #             filterText += '; {}="{}"'.format(colName, filter)
    #         elif isinstance(filter, tuple):
    #             filterText += '; {} < {} < {}'.format(filter[0], colName, filter[1])
    #         elif isinstance(filter, list):
    #             filterText += '; {} in {}"'.format(str(filter), colName)
    #     self.ui.lineEditFilterList.setText(filterText)
    #     tup = (colName, filter)
    #     self.filterList.append(tup)
    #     selectedStartDate = self.ui.DEFrom.date().toPyDate()
    #     selectedEndDate = self.ui.DEBis.date().toPyDate()
    #     match2 = ('Buchungstag', (selectedStartDate, selectedEndDate))
    #     self.filterList.append(match2)
    #
    #     currentConto = self.ui.cbActiveConto.currentText()
    #     if currentConto != 'all':
    #         match3 = ('myconto', currentConto)
    #         self.filterList.append(match3)
    #
    #     realExpenses = self.app_reale.plan_vs_real.filterRows(self.filterList)
    #     # #print(50*'Ü')
    #     # for i in self.filterList:
    #     #     #print('--', i)
    #     # #print()
    #     payments, income = self.app_reale.split_expenses_income(realExpenses)
    #     realExpenses = np.atleast_2d(payments)
    #     realIncome = np.atleast_2d(income)
    #     if realExpenses.shape == (1, 0):
    #         realExpenses = np.empty((0, len(self.app_reale.plan_vs_real.columnsNames)))
    #     if realIncome.shape == (1, 0):
    #         realIncome = np.empty((0, len(self.app_reale.plan_vs_real.columnsNames)))
    #     self.populateTableReal(realExpenses)
    #     self.populateTableIncome(realIncome)

    def add_income(self):
        self.chelt_db_connection.refresh_db()
        self.app_planned_income = Income(chelt_db=self.chelt_db_connection.chelt_db,
                                         income_table=self.chelt_db_connection.income_table)
        self.ui.TW_main_user_interface.setTabEnabled(1, True)
        self.ui.PB_add_income.setVisible(False)

    def add_real(self):
        self.ui.TW_main_user_interface.setTabEnabled(2, True)
        self.ui.PB_add_real.setVisible(False)
        self.app_reale = CheltuieliReale(chelt_db=self.chelt_db_connection.chelt_db,
                                         myAccountsTable=self.chelt_db_connection.myAccountsTable,
                                         imported_csv=self.chelt_db_connection.imported_csv,
                                         chelt_plan=self.chelt_db_connection.chelt_plan,
                                         plan_vs_real=self.chelt_db_connection.plan_vs_real,
                                         knowntrans=self.chelt_db_connection.knowntrans,
                                         sskm=self.chelt_db_connection.sskm,
                                         deubnk=self.chelt_db_connection.deubnk,
                                         n26=self.chelt_db_connection.n26,
                                         yearly_all=self.chelt_db_connection.yearly_all,
                                         id_users=self.user.id)

    def deleteItemsOfLayout(self, ui_groupbox):
        # #print('Module: {}, Class: {}, Def: {}'.format(__name__, __class__, sys._getframe().f_code.co_name))
        layout_grupa = ui_groupbox.layout()
        if layout_grupa is not None:
            while layout_grupa.count():
                item = layout_grupa.takeAt(0)
                widget = item.widget()
                if widget is not None:
                    widget.setParent(None)
                else:
                    self.deleteItemsOfLayout(item.layout())
            sip.delete(layout_grupa)

    def write_sql_yearly_plan(self):
        year = int(self.ui.SB_year.value())
        self.app_planned.write_sql_yearly_plan(year=year)

    def write_sql_yearly_all(self):
        year = int(self.ui.SB_year.value())
        self.app_planned.write_planned_expenses_yearly_all(year=year)
        self.app_planned.write_planned_income_yearly_all(year=year)

    def write_real_expenses_yearly_all(self):
        # year = int(self.ui.SB_year.value())
        self.app_reale.write_real_expenses_yearly_all()

    def write_real_income_yearly_all(self):
        # year = int(self.ui.SB_year.value())
        self.app_reale.write_real_income_yearly_all()

    def upload_download_file(self, item):
        print('Module: {}, Class: {}, Def: {}, Caller: {}'.format(__name__, __class__, sys._getframe().f_code.co_name,sys._getframe().f_back.f_code.co_name))
        if self.ui.TWsskm.horizontalHeaderItem(item.column()).text() == 'path2inp':
            indx_csv_id = None
            for ind in range(self.ui.TWsskm.columnCount()):
                if self.ui.TWsskm.horizontalHeaderItem(ind).text() == 'csv_id':
                    # print('BINGO', ind)
                    indx_csv_id = ind
                    break
            if item.text() != 'None':
                csv_id = self.ui.TWsskm.item(item.row(), indx_csv_id).text()
                self.app_reale.download_csv_file(csv_id=csv_id)
            else:
                print('upload')
                uploadFile, _ = QFileDialog.getOpenFileName(self, "upload file", "", "")
                # self.app.upload_file(uploadFile, id_)
                # self.populateDetailsTab()


class FilterWindow(QDialog):
    def __init__(self, colType, colName):
        super(FilterWindow, self).__init__()
        path2src, pyFileName = os.path.split(__file__)
        uiFileName = 'filterWindow.ui'
        path2GUI = os.path.join(path2src, 'GUI', uiFileName)
        Ui_MainWindow, QtBaseClass = uic.loadUiType(path2GUI)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        self.colName = colName
        self.ui.GB_DateInterval.setVisible(False)
        self.ui.GB_IntInterval.setVisible(False)
        self.ui.checkBoxDateInterval.stateChanged.connect(self.openDateInterval)
        self.ui.checkBoxIntInterval.stateChanged.connect(self.openIntInterval)

        self.rejected.connect(self.byebye)

        if colType == 'int':
            self.ui.GB_IntInterval.setVisible(True)
            self.ui.lineEdit_max.setEnabled(False)
        if colType == 'date':
            self.ui.GB_DateInterval.setVisible(True)
            self.ui.dateEditTo.setEnabled(False)

    def openIntInterval(self):
        if self.ui.checkBoxIntInterval.isChecked():
            self.ui.lineEdit_max.setEnabled(True)
            self.ui.label_int.setText('< {} <'.format(self.colName))
        else:
            self.ui.lineEdit_max.setEnabled(False)
            self.ui.label_int.setText('= {}'.format(self.colName))

    def openDateInterval(self):
        if self.ui.checkBoxDateInterval.isChecked():
            self.ui.dateEditTo.setEnabled(True)
            self.ui.label_date.setText('< {} <'.format(self.colName))
        else:
            self.ui.dateEditTo.setEnabled(False)
            self.ui.label_date.setText('= {}'.format(self.colName))

    def byebye(self):
        self.close()

    def intInterval(self):
        if self.ui.checkBoxIntInterval.isChecked():
            tup = (self.ui.lineEdit_min.text(), self.ui.lineEdit_max.text())
            return tup
        else:
            return self.ui.lineEdit_min.text()

    def dateInterval(self):
        if self.ui.checkBoxDateInterval.isChecked():
            tup = (self.ui.dateEditFrom.date(), self.ui.dateEditTo.date())
            return tup
        else:
            return self.ui.dateEditFrom.date()

    @staticmethod
    def getIntInterval(colName):
        dialog = FilterWindow('int', colName)
        result = dialog.exec_()
        filt = dialog.intInterval()
        if result == QDialog.Accepted:
            return filt
        else:
            return None

    @staticmethod
    def getDateInterval(colName):
        dialog = FilterWindow('date', colName)
        result = dialog.exec_()
        filt = dialog.dateInterval()
        if result == QDialog.Accepted:
            return filt
        else:
            return None


class AddRowWindow(QDialog):
    def __init__(self, id_users, table):
        super(AddRowWindow, self).__init__()
        path2src, pyFileName = os.path.split(__file__)
        uiFileName = 'AddRowWindow.ui'
        path2GUI = os.path.join(path2src, 'GUI', uiFileName)
        Ui_MainWindow, QtBaseClass = uic.loadUiType(path2GUI)

        self.table = table
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.grupa = self.ui.GB_add_identification
        caller = sys._getframe().f_back.f_code.co_name
        self.prepare_window(caller)
        self.rejected.connect(self.byebye)

    @property
    def category(self):
        all_vals = self.table.returnColumn('category')
        return list(set(all_vals))

    # @property
    # def table_columns(self):
    #     # all_vals = self.table.returnColumn('category')
    #     return self.table.columnsNames

    @property
    def contos(self):
        all_vals = self.table.returnColumn('myconto')
        return list(set(all_vals))

    def prepare_window(self, caller):
        if caller == 'add_transactions':
            self.ui.GB_add_conto.setVisible(False)
            self.ui.GB_add_identification.setVisible(False)
            self.ui.SB_freq.setValue(1)
            self.ui.DE_valid_from.setDate(datetime.now().date())
            self.ui.DE_valid_to.setDate(datetime.now().date())
            self.ui.DE_valid_from.setCalendarPopup(True)
            self.ui.DE_valid_to.setCalendarPopup(True)
            self.ui.CB_category.addItems(self.category)
            self.ui.CB_myConto.addItems(self.category)
            self.ui.CB_cancel_auto_ext.setVisible(False)
        elif caller == 'add_conto':
            self.ui.GB_add_transactions.setVisible(False)
            self.ui.GB_add_identification.setVisible(False)
        elif caller == 'get_identification_cols_for_knowntrans':
            self.ui.GB_add_conto.setVisible(False)
            self.ui.GB_add_transactions.setVisible(False)
            self.ui.GB_4chelt_plan.setVisible(False)
            # self.ui.GB_add_identification.setVisible(True)
            vbox = QGridLayout()
            for i, col in enumerate(self.table.columnsNames):
                box = QCheckBox(col)
                box.row = i
                vbox.addWidget(box)
            self.grupa.setLayout(vbox)
        elif caller == 'get_identification_cols_for_chelt_plan':
            self.ui.GB_add_conto.setVisible(False)
            self.ui.GB_add_transactions.setVisible(False)
            # self.ui.GB_add_identification.setVisible(True)
            vbox = QGridLayout()
            for i, col in enumerate(self.table.columnsNames):
                box = QCheckBox(col)
                box.row = i
                vbox.addWidget(box)
            self.grupa.setLayout(vbox)

    def byebye(self):
        self.close()

    def get_conto_name_and_bank(self):
        tup = (self.ui.LE_conto_name.text(), self.ui.CB_bank_name.currentText())
        return tup

    def get_add_transaction_variables(self):
        category = self.ui.CB_category.currentText()
        name = self.ui.LE_name.text()
        value = self.ui.LE_value.text()
        myconto = self.ui.CB_myConto.currentText()
        freq = self.ui.SB_freq.value()
        pay_day = self.ui.SB_pay_day.value()
        valid_from = self.ui.DE_valid_from.date().toPyDate()
        valid_to = self.ui.DE_valid_to.date().toPyDate()
        auto_ext = False
        if self.ui.CB_auto_ext.isChecked():
            auto_ext = True
        identification = None
        cancel_auto_ext = False
        if self.ui.CB_cancel_auto_ext.isChecked():
            cancel_auto_ext = True

        tup = (category, name, value, myconto, freq, pay_day, valid_from, valid_to, auto_ext, identification, cancel_auto_ext)
        return tup

    def get_identification_variables_for_knowntrans(self):
        identifications_cols = []
        layout_grupa = self.grupa.layout()
        for row in range(layout_grupa.count()):
            item = layout_grupa.itemAt(row)
            widget = item.widget()
            if isinstance(widget, QCheckBox):
                if widget.isChecked():
                    # print('widget.text()', widget.text())
                    identifications_cols.append(widget.text())
        category = self.ui.CB_category.currentText()
        name = self.ui.LE_name.text()
        add_known_transaction = {'category': category,
                                 'name': name,
                                 'identification': identifications_cols}
        return add_known_transaction

    def get_identification_variables_for_chelt_plan(self):
        category = self.ui.CB_category.currentText()
        name = self.ui.LE_name.text()
        freq = self.ui.SB_freq.value()
        valid_from = self.ui.DE_valid_from.date().toPyDate()
        valid_to = self.ui.DE_valid_to.date().toPyDate()
        auto_ext = False
        if self.ui.CB_auto_ext.isChecked():
            auto_ext = True

        identifications_cols = []
        layout_grupa = self.grupa.layout()
        for row in range(layout_grupa.count()):
            item = layout_grupa.itemAt(row)
            widget = item.widget()
            if isinstance(widget, QCheckBox):
                if widget.isChecked():
                    # print('widget.text()', widget.text())
                    identifications_cols.append(widget.text())
        add_known_transaction = {'category': category,
                                 'name': name,
                                 'freq': freq,
                                 'valid_from': valid_from,
                                 'valid_to': valid_to,
                                 'auto_ext': auto_ext,
                                 'identification': identifications_cols}
        return add_known_transaction

    @staticmethod
    def add_conto(id_users, table):
        dialog = AddRowWindow(id_users, table)
        result = dialog.exec_()
        filt = dialog.get_conto_name_and_bank()
        if result == QDialog.Accepted:
            return filt
        else:
            return None

    @staticmethod
    def add_transactions(id_users, table):
        dialog = AddRowWindow(id_users, table)
        result = dialog.exec_()
        filt = dialog.get_add_transaction_variables()
        if result == QDialog.Accepted:
            return filt
        else:
            return None

    @staticmethod
    def get_identification_cols_for_knowntrans(id_users, table):
        dialog = AddRowWindow(id_users, table)
        result = dialog.exec_()
        filt = dialog.get_identification_variables_for_knowntrans()
        if result == QDialog.Accepted:
            return filt
        else:
            return None

    @staticmethod
    def get_identification_cols_for_chelt_plan(id_users, table):
        dialog = AddRowWindow(id_users, table)
        result = dialog.exec_()
        filt = dialog.get_identification_variables_for_chelt_plan()
        if result == QDialog.Accepted:
            return filt
        else:
            return None


def main():
    chelt_db = chelt_db_connection(rappmysql.ini_chelt)
    users_db = users_db_connection(rappmysql.ini_users)

    app = QApplication(sys.argv)
    window = MyApp(users_db, chelt_db)
    window.show()
    # sys.exit(app.exec_())
    app.exec_()


if __name__ == '__main__':
    main()
