import numpy as np
import datetime as dt
import sys
import os
import rappmysql
from rappmysql.mysqlquerys import connect
from rappmysql.mysqlquerys import mysql_rm

np.set_printoptions(linewidth=250)
__version__ = 'V1'


class DB_Connection:
    def __init__(self, ini_masina):
        if isinstance(ini_masina, dict):
            self.credentials = ini_masina
        else:
            self.conf = connect.Config(ini_masina)
            self.credentials = self.conf.credentials

        if not isinstance(self.credentials, dict):
            raise RuntimeError('Credentials not dict')
        self.chelt_db = self.sql_rm.DataBase(self.credentials)
        if not self.chelt_db.is_connected:
            raise RuntimeError('Could not connect to database')
        # print('Connected to database:{}'.format(self.credentials['database']), self.chelt_db.is_connected)
        self.refresh_db()

    def refresh_db(self):
        # print(100*'refresh_db')
        self.chelt_plan = self.sql_rm.Table(self.conf.credentials, 'chelt_plan')

    @property
    def sql_rm(self):
        if self.conf.db_type == 'mysql':
            sql_rm = mysql_rm
        return sql_rm

    def close_connection(self):
        self.chelt_db.db.close()
        # self.chelt_plan.close()
        # self.yearly_plan.close()


class CheltPlanificate:
    def __init__(self, chelt_plan):
        self.chelt_plan = chelt_plan

    @property
    def sql_rm(self):
        # print('Module: {}, Class: {}, Def: {}'.format(__name__, __class__, sys._getframe().f_code.co_name))
        if self.conf.db_type == 'mysql':
            sql_rm = mysql_rm
        return sql_rm

    def get_all_rows_from_table(self, tableHead):
        # print(sys._getframe().f_code.co_name, tableHead)
        # table_documente = mysql_rm.Table(self.conf.credentials, 'chelt_plan')
        # all_docs_databases = table_documente.returnColumn('Name')
        all_chelt = []
        check = all(item in list(self.chelt_plan.columnsProperties.keys()) for item in tableHead)
        if check:
            print('ÖÖÖÖÖÖ')
            vals = self.chelt_plan.returnColumns(tableHead)
            for row in vals:
                row = list(row)
                row.insert(0, 'chelt_plan')
                all_chelt.append(row)
        newTableHead = ['table']
        for col in tableHead:
            newTableHead.append(col)

        return newTableHead, all_chelt

    def excludeNone(self, tableHead, table):
        if None in table[:, tableHead.index('valid_to')]:
            newTable = table[table[:, tableHead.index('valid_to')] != np.array(None)]
        return tableHead, newTable

    def get_days_to_expire(self, tableHead, table):
        print(sys._getframe().f_code.co_name, tableHead)

        newTableHead = []
        for col in tableHead:
            newTableHead.append(col)
        newTableHead.append('days2Expire')

        newCol = np.empty((table.shape[0], 1), dtype=object)
        newCol.fill('')
        table = np.append(table, newCol, 1)
        for row in table:
            expDate = row[tableHead.index('valid_to')]
            today = dt.date.today()
            if expDate is not None:
                time2exp = (expDate - today).days
                row[-1] = time2exp
        return newTableHead, table

    def get_days_to_expire_with_auto_ext(self, tableHead, table):
        print(sys._getframe().f_code.co_name, tableHead)

        newTableHead = []
        for col in tableHead:
            newTableHead.append(col)
        newTableHead.append('days2Expire')

        newCol = np.empty((table.shape[0], 1), dtype=object)
        newCol.fill('')
        table = np.append(table, newCol, 1)

        for row in table:
            # print('row****', row)

            expDate = row[tableHead.index('valid_to')]
            valid_from = row[tableHead.index('valid_from')]
            # print('expDate#####****', expDate, tableHead.index('valid_to'))
            today = dt.date.today()
            if expDate is not None:
                time2exp = (expDate - today).days
                row[-1] = time2exp
            elif expDate is None:
                print(row)
                print(valid_from, type(valid_from))
                #todo aici am ramas
        return newTableHead, table

    def hideExpired(self, tableHead, table):
        print(sys._getframe().f_code.co_name, tableHead)
        newTable = table[table[:, tableHead.index('days2Expire')] > 0]
        return tableHead, newTable

    def relevantOnly(self, tableHead, table, days):
        print(sys._getframe().f_code.co_name, tableHead)
        # colIndx = tableHead.index('path')
        # indxPath = [x for x, item in enumerate(table[:, colIndx]) if (item == '' or item is None)]
        colIndx = tableHead.index('days2Expire')
        indxExp = [x for x, item in enumerate(table[:, colIndx]) if item != '' and 0 < item < days]
        indx = [ *indxExp] #*indxPath,
        indx = list(set(indx))
        newTable = table[indx]
        return tableHead, newTable


def main():
    chelt_db_connection = DB_Connection(rappmysql.ini_chelt)
    tableHead = ['id', 'name', 'freq', 'valid_from', 'valid_to', 'auto_ext']

    expiry_chelt_plan = CheltPlanificate(chelt_db_connection.chelt_plan)
    newTableHead, all_sql_files = expiry_chelt_plan.get_all_rows_from_table(tableHead)
    all_sql_files = np.atleast_2d(all_sql_files)
    # tableHead, all_sql_files = expiry_chelt_plan.excludeNone(newTableHead, all_sql_files)
    # tableHead, all_sql_files = expiry_chelt_plan.get_days_to_expire(tableHead, all_sql_files)
    # # if self.ui.CB_hideExpired.isChecked():
    # # tableHead, all_sql_files = table.excludeNone(tableHead, all_sql_files)
    # tableHead, all_sql_files = expiry_chelt_plan.hideExpired(tableHead, all_sql_files)
    #

    tableHead, all_sql_files = expiry_chelt_plan.get_days_to_expire_with_auto_ext(newTableHead, all_sql_files)
    for ii in all_sql_files:
        print('##ii', ii)
    # print(newTableHead)


if __name__ == '__main__':
    main()
