#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""Saver_Ausw_Erspar v1.2.1.4 _py31403 Git Version"""

# %% === Imports
# benötigte Packages
import logging
import tkinter as tk  # noqa: F401
from datetime import datetime
from pathlib import Path
from time import sleep
from time import time

import xlwings as xw

from eSaver_Data_App import App_Data
from eSaver_Data_XLS import XLS_Data  # noqa: F401
from eSaver_utils import logger_Off
from eSaver_utils import logger_On
from eSaver_utils import logger_Settings


# %% === Variables Global anlegen
app_data = App_Data()

debug_main = False

pass  # ## ==========


# ? =============================================
# ## === Erspar-Funktionen
# %% === Liste_nach_Name_suchen
def liste_nach_name_scan(listToScan: list, scan: str) -> int:
    """Liste wird nach Inhalt gescannt

    Args:
        listToScan (list): zu durchsuchende Liste
        scan (str): zu suchender Text

    Returns:
        int: Indes vom Text in der liste
            0 = Text nicht gefunden
    """
    if scan in listToScan:
        cnt = 1 + listToScan.index(scan)
        return cnt

    return 0


# %% === excel_read_inits_exportFiles
def excel_read_inits_exportFiles(list_Col_A: list, sht) -> int:
    """schreiben der Export-Dateien in add_Data

    (Excel)ExportFiles => app_data.tupl_strExportFile

    Args:
        list_Col_A (list): Spalte, die durchsucht werden soll
        sht (Sheets): Excel-Tabellen in der gesucht wird

    Returns:
        int: Anzahl der gefundenen Positionen
    """
    # Tuble in Liste umwandeln
    list_strExportFile = list(app_data.tupl_strExportFile)
    list_strImportFile = list(app_data.tupl_strImportFile)
    list_Postfix = list(app_data.list_Postfix)

    # scan's Export-VIDA Dateien
    scan_col = app_data.intExcelInitValue
    strPraefix = 'Export_File'

    strSearch = ''
    cnt = 0
    for i in range(len(list_Postfix)):
        # scannen der Excel-Datei
        strSearch = strPraefix + list_Postfix[cnt]
        scan_row = liste_nach_name_scan(list_Col_A, strSearch)
        if scan_row:
            list_strExportFile[i] = sht.range((scan_row, scan_col)).value
        else:
            print('Wert NICHT gefunden')
        cnt += 1

    pass  # Debug

    # Liste in Tuble zurück schreiben
    app_data.tupl_strExportFile = list(list_strExportFile)
    app_data.tupl_strImportFile = list(list_strImportFile)

    return cnt


# %% === excel_read_inits_exportFiles
def excel_write_inits_importFiles(list_Col_A: list, sht) -> int:
    """schreiben der Import-Dateien in add_Data

    (Excel)ImportFiles => app_data.tupl_strImportFile

    Args:
        list_Col_A (list):  Spalte, die durchsucht werden soll
        sht (Sheets): Excel-Tabellen in der gesucht wird

    Returns:
        int: Anzahl der gefundenen Positionen
    """
    # Tuble in Liste umwandeln
    list_strExportFile = list(app_data.tupl_strExportFile)
    list_strImportFile = list(app_data.tupl_strImportFile)
    list_Postfix = list(app_data.list_Postfix)

    # scan's Import-VIDA Dateien
    scan_col = app_data.intExcelInitValue
    strPraefix = 'Import_File'

    strPostfix_File = '_Imp.xlsx'
    strSearch = ''
    cnt = 0

    for i in range(len(list_Postfix)):
        # ImportFile Name bilden
        strImportFile = conv_ExportFiles_from_ImportFiles(list_strExportFile[i], strPostfix_File)
        list_strImportFile[i] = strImportFile
        # scannen der Excel-Datei
        strSearch = strPraefix + list_Postfix[cnt]
        scan_row = liste_nach_name_scan(list_Col_A, strSearch)
        if scan_row:
            sht.range((scan_row, scan_col)).value = list_strImportFile[i]
        else:
            print(f'scan: {scan_row} - Wert NICHT gefunden')
        cnt += 1

    pass  # debug

    # Liste in Tuble zurück schreiben
    app_data.tupl_strExportFile = list(list_strExportFile)
    app_data.tupl_strImportFile = list(list_strImportFile)

    return cnt


# %% === conv_ExportFiles_from_ImportFiles
def conv_ExportFiles_from_ImportFiles(ExportFile: str, Postfix: str) -> str:
    """ImportFile-Name von ExportFile-Name generieren


    Args:
        ExportFile (str): Export-File
        Postfix (str): PostFix Erweiterung zum Austauschen

    Returns:
        RC (str): String value, conv_ImportFile
    """

    strTemp_File = ExportFile
    strTemp_split = strTemp_File.split('_')
    strTemp_split.pop()
    strTemp_File = '_'.join(strTemp_split)
    strTemp_File += Postfix

    strImportFile = strTemp_File

    return strImportFile


# %% === excel_read_Inits
def excel_read_inits():
    """lesen der Export-Datei in add_Data

    alle dateien
    """
    tStart = time()  # todo: Zeitmessung
    strTimeFtime = datetime.now().strftime(app_data.strftime_format)
    logging.info(f'excel_read_inits - started                                   / Start {strTimeFtime}')

    print('Start -> def excel_read_inits')

    wb = xw.Book.caller()
    sheet = wb.sheets[0]
    sheet = wb.sheets['Export-VIDA Main']

    sheet['A6'].value = 'call_1: excel_read_inits in Arbeit!'
    print('eSaver_Ausw_1_xlsm_Init_reads - excel_read_inits: ' + 'excel_read_inits in Arbeit')

    print('wait for XLwings')
    sleep(1)  # warten bis excel geladen wurde
    pass

    # max_count abfragen
    sht = wb.sheets[0]
    last_row = sht.used_range.last_cell.row
    last_col = sht.used_range.last_cell.column
    sht.range('A7').value = f'last_row: {last_row}'
    sht.range('A8').value = f'last_col: {last_col}'

    # Loop über Spalte
    list_Col_A = []
    for i in range(1, last_row + 1):
        value_tmp = sht.range((i, 1)).value
        list_Col_A.append(value_tmp)

    print(list_Col_A)

    # Init-Value Export-VIDA einlesen
    cnt_export = excel_read_inits_exportFiles(list_Col_A, sht)
    print(cnt_export)
    pass

    # Init-Value Import-VIDA Name erstellen
    cnt_import = excel_write_inits_importFiles(list_Col_A, sht)
    print(cnt_import)

    pass

    sheet['A6'].value = 'call_1: excel_read_inits Fertig!'
    print('eSaver_Ausw_1_xlsm_Init_reads - excel_read_inits: ' + 'excel_read_inits Fertig')

    pass

    print('Stopp -> def excel_read_inits')

    tEnde = time()  # todo: Zeitmessung
    tDauer = tEnde - tStart
    logging.info(f'main_app_init - finished                                     / tDauer {tDauer}')

    return


# %% === main_app_init
def main_app_init():
    """___

    ___
    """
    tStart = time()  # todo: Zeitmessung
    strTimeFtime = datetime.now().strftime(app_data.strftime_format)
    logging.info(f'main_app_init - started                                      / Start {strTimeFtime}')

    print('Start -> def main_app_init')
    print(f'>>> {app_data.strPath_parent}\n>>> {app_data.strPath_cwd} ')

    if not debug_main:
        xw.Book.caller()
    else:
        strXlsm_FileNameMain = app_data.strXlsm_FileNameMain
        xw.Book(strXlsm_FileNameMain).set_mock_caller()

    excel_read_inits()

    # ! test ob übernommen
    print('--' * 40)
    for ExportFile in app_data.tupl_strExportFile:
        print(f'ExportFile: {ExportFile}')

    # ! test ob übernommen
    print('--' * 40)
    for ImportFile in app_data.tupl_strImportFile:
        print(f'ImportFile: {ImportFile}')

    pass

    print('Stopp -> def main_app_init')

    tEnde = time()  # todo: Zeitmessung
    tDauer = tEnde - tStart
    logging.info(f'main_app_init - finished                                     / tDauer {tDauer}')

    return


# * =============================================
# ? =============================================
# %% === main_app
def main_app():
    """eSaver_Ausw_Erpar zum Abfragen der Excel-Listen

    Note:
        Parameter werden über XLSX definiert

    Args:
        none:

    Returns:
        none:
    """
    tStart = time()  # todo: Zeitmessung
    strTimeFtime = datetime.now().strftime(app_data.strftime_format)
    logging.info(f'main_app - started                                           / Start {strTimeFtime}')

    # ## ==========                                     # INIT ggf über parameter
    main_app_init()

    # ## ==========

    tEnde = time()  # todo: Zeitmessung
    tDauer = tEnde - tStart
    logging.info(f'main_app - finished                                          / tDauer {tDauer}')

    return


# %% === main
def main():
    """main Programm

    INIT Eintagungen aus Excel lesen
    in App_Data eintragen
    """
    tStart = time()  # todo: Zeitmessung

    DEBUG = 1

    # ## === Variables Global anlegen
    # app_data = App_Data()

    strTimeFtime = datetime.now().strftime(app_data.strftime_format)

    # ## === Path-Variablen holen ===
    cwd = Path.cwd()
    parent = cwd.parent

    app_data.strPath_cwd = cwd
    app_data.strPath_parent = parent
    app_data.strPath_type_cwd = type(cwd)

    # ========== logger aktivieren ==========
    # ?: Hier sollte der Dateiname aus der App_Data.xx gelesen werden.
    logger_On(parent, 'x_eSaver_Ausw_1_reads_excel_inits_Log_')
    logger_Settings()

    strTimeFtime = datetime.now().strftime(app_data.strftime_format)
    logging.info(f'app_main - started                                           / Start {strTimeFtime}')

    pass

    # ========== main_app ==========
    main_app()

    pass

    tEnde = time()  # todo: Zeitmessung
    tDauer = tEnde - tStart
    logging.info(f'app_main - finished                                          / tDauer {tDauer}')

    logger_Off()

    return


# %% === Start __main__ ==========
if __name__ == '__main__':
    """Einsprung Start der Anlage

    """
    pass

    debug_main = True
    main()

    pass  # ## ==========


# %% === EOF
# EOF                   // End of File
