'''Created Jul 7, 2021 Levi'''
import os
# import platform
import warnings
import sqlite3
import shutil
import platform
import subprocess as sp
from dataclasses import dataclass
from xml.etree import ElementTree as ET
import pandas as pd
from pandas import DataFrame as df  # @UnusedImport
# from bs4 import BeautifulSoup
from . import consts

def get_prof_folder():
    us_profile = consts.PROFILE
    teamnet = consts.TEAMNET
    path = os.path.join(us_profile, teamnet)
    conf_folder = list(filter(lambda f: consts.CONF in f, os.listdir(path)))[0]
    path = os.path.join(path, conf_folder)
    return path

def get_db_folder():
    # us_profile = consts.PROFILE
    # path = os.path.join(us_profile, consts.TEAMNET)
    # db_folder = list(filter(lambda f: 'Revisal' in f, os.listdir(path)))[0]
    # path = os.path.join(path, db_folder)
    f = get_conf_file()
    tree = ET.parse(f)
    root = tree.getroot()
    for child in root.iter('setting'):
        if child.attrib['name'] == 'RootFolder':
            for value in child.iter('value'):
                path = value.text
    return path.replace('\\', '/')

def get_conf_file():
    ver = os.listdir(get_prof_folder())[-1]
    ver_folder = os.path.join(get_prof_folder(), ver)
    conf_file = os.path.join(ver_folder, consts.CONF_FILE)
    return conf_file

def file_open(file_name):
    abs_path = os.path.abspath(file_name)
    if platform.system() == 'Windows':
        sp.run(f'start {abs_path}', shell=True)
    elif platform.system() == 'Linux':
        sp.run(['xdg-open', f'{abs_path}'])
    else:
        raise NotImplementedError


warnings.filterwarnings('ignore', module='xlsxwriter')

@dataclass
class Account:
    name: str = None
    folder: str = None
    id: str = None
    updated: bool = None
    imported: bool = None


class ReviSal(object):
    '''
    classdocs
    '''
    def __init__(self, employer=None):
        '''
        Constructor
        '''
        self._us_profile = get_prof_folder()
        self._conf_file = get_conf_file()
        self._revisal_tree = ET.parse(self._conf_file)
        self._db_folder = get_db_folder()
        self.root = self._revisal_tree.getroot()
        if employer:
            self.con = self.connect(employer)

    @property
    def ver(self):
        return os.listdir(self._us_profile)[-1]

    def accounts(self):
        self._accounts = []
        for child in self.root.iter('AngajatorInfo'):
            account = Account()
            for name, dir_, ident, isupd, isimport in zip(child.iter('Nume'), child.iter('Folder'), child.iter('Identificator'), child.iter('IsUpdated'), child.iter('IsImportFinished')):
                account.name = name.text
                account.folder = dir_.text
                account.id = ident.text
                account.updated = isupd.text
                account.imported = isimport.text
            self._accounts.append(account)
        return self._accounts

    def connect(self, employer=None):  # mode='audit'
        if employer:
            empl = self.get_employer(employer)
        else:
            accounts = self.accounts()
            for ind, account in enumerate(accounts):
                print(ind, account)
            select = int(input(f'type number from 0 to {len(accounts) - 1} '))
            empl = accounts[select]
        db = os.path.join(self._db_folder, empl.folder, consts.DB_NAME)
        self.con = sqlite3.connect(f'file:{db}?mode=ro', uri=True)
        return self.con

    def create_df(self, mode):
        '''
        accepted modes:
        -> single,
        -> audit
        '''
        with open(consts.QUERY[mode]) as sql_query:
            query = sql_query.read()
        self.df = pd.read_sql_query(
            query,
            self.con,
            parse_dates=['DataContract', 'DataInceput', 'DataConsemn', 'DataIncetare']
        )
        # if self.df['NumeSal'] != self.df['NumeSal'].shift(+1):
        mask = self.df['NumeSal'] != self.df['NumeSal'].shift(+1)
        self.df['mask'] = mask
        self.df['sal. dif.'] = self.df['Salariu'] / self.df['Salariu'].shift(+1)
        self.df['sal. dif.'] = [dif if cond is False else '' for cond, dif in zip(self.df['mask'], self.df['sal. dif.'])]
        # else:
        #     self.df['sal. dif.'] = 0
        self.df['sal. min.'] = consts.SAL_MIN
        return self.df

    def emp_details(self):
        with open(consts.DQUERY['emp_details']) as sql_query:
            query = sql_query.read()
        self.ddf = pd.read_sql_query(
            query,
            self.con,
        )
        return self.ddf

    def make_xlsm(self, fname='rvs.xlsx'):  # employer, mode='audit'
        # df = self.connect(employer, mode)
        # fname = 'rvs.xlsx'
        writer = pd.ExcelWriter(
            fname,
            engine='xlsxwriter',
            date_format='mmmm dd yy',
            datetime_format='dd-mmm-yy'
        )
        self.df.to_excel(writer, sheet_name='Contracte', index=True)
        self.ddf.to_excel(writer, sheet_name='Angajator', index=True)
        workbook = writer.book
        workbook.add_vba_project('./vbaProject.bin')

        angajator = writer.sheets['Angajator']
        contracte = writer.sheets['Contracte']
        contracte.freeze_panes(1, 0)
        angajator.freeze_panes(1, 0)
        contracte.autofilter('A1:T500')
        set_columns = {
            'A:A': 5,
            'B:B': 23,
            'C:C': 5,
            'D:D': 12,
            'E:E': 12,
            'H:H': 12,
            'L:L': 12,
            'P:P': 10
        }
        for column, width in set_columns.items():
            contracte.set_column(column, width)
            angajator.set_column(column, width)
        writer.save()
        writer.close()
        shutil.move('rvs.xlsx', 'rvs.xlsm')

    def bulk_create(self):
        accounts = self.accounts()
        bulk_df = []
        for account in accounts:
            self.connect(employer=account.name)
            ddf = self.emp_details()
            # print(ddf['NumeAng'])
            df = self.create_df(mode='simple')
            df['angajator'] = ddf['NumeAng']
            df['angajator'] = df['angajator'].fillna(method='ffill')
            bulk_df.append(df)
        bulk_df = pd.concat(bulk_df, ignore_index=True)
        # print(bulk_df)
        writer = pd.ExcelWriter(
            'bulk.xlsx',
            engine='xlsxwriter',
            date_format='mmmm dd yy',
            datetime_format='dd-mmm-yy'
        )
        bulk_df.to_excel(writer)
        workbook = writer.book
        workbook.add_vba_project('./vbaProject.bin')
        sh = writer.sheets['Sheet1']
        sh.freeze_panes(1, 0)
        sh.autofilter('A1:V500')
        writer._save()
        writer.close()
        shutil.move('bulk.xlsx', 'bulk.xlsm')
        self.bulk_df = bulk_df
        return self.bulk_df

    def get_employer(self, employer):
        accs = self.accounts()
        for empl in range(len(accs)):
            if employer in accs[empl].name:
                return accs[empl]
