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

"""Saver_Ausw_Erspar openpyxl Excel Import zu Excel Ausw"""

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

import xlwings as xw
import openpyxl as ox

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

from eSaver_utils_read_excel_to_App_data import main_app_read_Init as eSaver_main_app_read_Init

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

debug_main = False

wb_ImpF = ''  # ImportFile [excel]
ws_ImpF = ''

wb_Dest = ''  # Destination [excel]
ws_Dest = ''

fileNameImpF = ''
fileNameDest = ''

ws_Mapp_Py_count_row = 0
ws_Mapp_Py_count_column = 0


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


# ? =============================================
# ? =============================================
# %% === main_app_Data
def copy_values_ImpF_to_Dest_cell(ws_ImpF_row, ws_ImpF_col, ws_Dest_row, ws_Dest_col):
    """einzele Zelle kopieren

    Args:
        ws_ImpF_row (int): row von der ImportFile-Datei
        ws_ImpF_col (int): col von der ImportFile-Datei
        ws_Dest_row (int): row von der Destination-Datei
        ws_Dest_col (int): col von der Destination-Datei

    Retruns:
        none:
    """
    global wb_ImpF
    global ws_ImpF

    global wb_Dest
    global ws_Dest

    ImpF_row = ws_ImpF_row
    ImpF_col = ws_ImpF_col

    Dest_row = ws_Dest_row
    Dest_col = ws_Dest_col

    ImpF_Value = ws_ImpF.cell(row=ImpF_row, column=ImpF_col).value
    ws_Dest.cell(row=Dest_row, column=Dest_col).value = ImpF_Value

    return


# %% === main_app_Data
def copy_values_ImpF_to_Dest():
    tStart = time()  # todo: Zeitmessung
    app_data_strftime_format = '%y.%m.%d %H:%M:%S:%f'
    strTimeFtime = datetime.now().strftime(app_data_strftime_format)
    logging.info(f'copy_values_ImpF_to_Dest started                             / Start {strTimeFtime}')

    global wb_ImpF
    global ws_ImpF

    global wb_Dest
    global ws_Dest

    ws_ImpF_Mapp_Py_row = ws_ImpF.max_row - 1
    ws_ImpF_Mapp_Py_column = ws_ImpF.max_column

    ws_Dest_Mapp_Py_row = ws_Dest.max_row - 1
    ws_Dest_Mapp_Py_column = ws_Dest.max_column

    if ws_ImpF_Mapp_Py_row < ws_Dest_Mapp_Py_row:
        # print(f'Bereich reicht nicht aus: ws_ImpF_Mapp_Py_count_row: {ws_ImpF_Mapp_Py_count_row}')
        # print(f'Bereich reicht nicht aus: ws_Dest_Mapp_Py_count_row: {ws_Dest_Mapp_Py_count_row}')
        pass
    else:
        exit(-3)

    # ! Kopfdaten übernehmen 4x
    ImpF_row = 1
    ImpF_col = 2

    Dest_row = 6
    Dest_col = 2

    for i in range(4):
        copy_values_ImpF_to_Dest_cell(
            ws_ImpF_row=ImpF_row, ws_ImpF_col=ImpF_col + i,
            ws_Dest_row=Dest_row, ws_Dest_col=Dest_col + i,
        )  # fmt: skip

    # ! Werte übergeben Spalte 1
    ImpF_row = 2
    ImpF_col = 1

    Dest_row = 9
    Dest_col = 1

    for i in range(ws_ImpF_Mapp_Py_row):
        copy_values_ImpF_to_Dest_cell(
            ws_ImpF_row=ImpF_row + i, ws_ImpF_col=ImpF_col,
            ws_Dest_row=Dest_row + i, ws_Dest_col=Dest_col,
        )  # fmt: skip

    # ! Werte übergeben Spalte 2
    ImpF_row = 2
    ImpF_col = 2

    Dest_row = 9
    Dest_col = 2

    for i in range(ws_ImpF_Mapp_Py_row):
        copy_values_ImpF_to_Dest_cell(
            ws_ImpF_row=ImpF_row + i, ws_ImpF_col=ImpF_col,
            ws_Dest_row=Dest_row + i, ws_Dest_col=Dest_col,
        )  # fmt: skip

    # ! Werte übergeben Spalte 3
    ImpF_row = 2
    ImpF_col = 3

    Dest_row = 9
    Dest_col = 3

    for i in range(ws_ImpF_Mapp_Py_row):
        copy_values_ImpF_to_Dest_cell(
            ws_ImpF_row=ImpF_row + i, ws_ImpF_col=ImpF_col,
            ws_Dest_row=Dest_row + i, ws_Dest_col=Dest_col,
        )  # fmt: skip

    # ! Werte übergeben Spalte 4
    ImpF_row = 2
    ImpF_col = 4

    Dest_row = 9
    Dest_col = 4

    for i in range(ws_ImpF_Mapp_Py_row):
        copy_values_ImpF_to_Dest_cell(
            ws_ImpF_row=ImpF_row + i, ws_ImpF_col=ImpF_col,
            ws_Dest_row=Dest_row + i, ws_Dest_col=Dest_col,
        )  # fmt: skip

    # ! Werte übergeben Spalte 5
    ImpF_row = 2
    ImpF_col = 5

    Dest_row = 9
    Dest_col = 5

    for i in range(ws_ImpF_Mapp_Py_row):
        copy_values_ImpF_to_Dest_cell(
            ws_ImpF_row=ImpF_row + i, ws_ImpF_col=ImpF_col,
            ws_Dest_row=Dest_row + i, ws_Dest_col=Dest_col,
        )  # fmt: skip

    pass

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

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

    return


# %% === main_app_Data
def main_app_Data():
    """Aufruf Verteiler der einzelnen scan's

    hier werden die Schritte pro Datei-Konvertierung ausgeführt.

    Note:
        Übergabe wird über globale Variablen umgesetzt,
        openpyxl sollte global gehalten werden.


    Args:
        global-wb (Workbook): excel-tabelle von geöffneter Datei
        global-ws (Sheet): excel-tabelle von geöffneter Datei

    Returns:
        none:
    """
    tStart = time()  # todo: Zeitmessung
    app_data_strftime_format = '%y.%m.%d %H:%M:%S:%f'
    strTimeFtime = datetime.now().strftime(app_data_strftime_format)
    logging.info(f'main_app_Data started                                        / Start {strTimeFtime}')

    global wb_ImpF
    global ws_ImpF

    global wb_Dest
    global ws_Dest

    cwd = Path.cwd()
    parent = cwd.parent
    str_path = app_data.strPath_Import_Files
    path_Import_Files = Path(str_path)
    file_path_Impf = path_Import_Files / fileNameImpF
    print(f'file_path_Impf: {file_path_Impf}')

    try:
        wb_ImpF = ox.load_workbook(filename=file_path_Impf, data_only=True)
        ws_ImpF = wb_ImpF.active
    except Exception as e:
        e2 = sys.exc_info()[1]
        print(f'Error Code InvalidFileException: \n {e} - {e2}')

        wb = xw.Book.caller()
        sheet = wb.sheets[0]
        displaytext = wb.macro('module1.pyDisplayText')
        displaytext(f'Error Code InvalidFileException: \n {e}')
        exit(-1)

    cwd = Path.cwd()
    parent = cwd.parent
    str_path = app_data.strPath_Export_Files
    path_ExportFile = Path(str_path)
    file_path_Dest = path_ExportFile / fileNameDest
    print(f'file_path_Dest: {file_path_Dest}')

    try:
        wb_Dest = ox.load_workbook(filename=file_path_Dest, data_only=False)
        ws_Dest = wb_Dest.active
    except Exception as e:
        e2 = sys.exc_info()[1]
        print(f'Error Code InvalidFileException: \n {e} - {e2}')

        wb = xw.Book.caller()
        sheet = wb.sheets[0]
        displaytext = wb.macro('module1.pyDisplayText')
        displaytext(f'Error Code InvalidFileException: \n {e}')
        exit(-2)

    listSheets_ImpF = wb_ImpF.sheetnames
    print(f'#>: listSheets_Source:  {listSheets_ImpF}')

    listSheets_Dest = wb_Dest.sheetnames
    print(f'#>: listSheets_Dest:  {listSheets_Dest}')

    ImpF_FileName = fileNameImpF
    ImpF_TableName = listSheets_ImpF[0]

    ImpF_FileName_split = ImpF_FileName.split('-')
    ImpF_Dest_TableName = ImpF_FileName_split[1][5:12]

    row = 2
    col = 1
    ImpF_Datum = ws_ImpF.cell(row=row, column=col).value

    # prüfen ob Vorgabe-Tabelle vorhanden ist
    pass
    print(f'Tabelle: {ImpF_Dest_TableName} wird gescannt ...', end=' ')
    if ImpF_Dest_TableName in listSheets_Dest:
        ws_Dest = wb_Dest[ImpF_Dest_TableName]
        print(f'..> {ImpF_Dest_TableName} wurde gefunden')

    else:
        exit(-1)

    # ja datum abfragen
    row = 9
    col = 1
    Dest_Datum = ws_Dest.cell(row=row, column=col).value

    # * __
    pass
    copy_values_ImpF_to_Dest()

    wb_ImpF.close()
    wb_Dest.save(file_path_Dest)
    wb_Dest.close()

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

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

    return


# %% === main_app
def main_app():
    """eSaver_Ausw_Erpar excel Importdateien lesen und in Ausw_Erspar-Excel schreiben,

    Loop über die Monats-Dateien

    Note:
        Übergabe wird über globale Variablen umgesetzt,
        openpyxl sollte global gehalten werden.

    Args:
        global-wb (Workbook): excel-tabelle von geöffneter Datei
        global-ws (Sheet): excel-tabelle von geöffneter Datei

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

    global fileNameImpF
    global fileNameDest

    # app_Data Excel-Datei einlesen
    # read_excel_inits()

    eSaver_main_app_read_Init(app_data)

    print(f'len(app_data.tupl_strImportFile) {len(app_data.tupl_strImportFile)}')
    print(f'strXlsm_FileNameDest:  {app_data.strXlsm_FileNameDest}')

    for fileLoop in range(0, 12):  # !=> range(0, 12)
        fileNameImpF = app_data.tupl_strImportFile[fileLoop]
        fileNameDest = app_data.strXlsm_FileNameDest
        print(f'=>> Srce: fileNameSource: {fileNameImpF}\n_>> Desk: fileNameDest: {fileNameDest} \n')
        logging.info(f'main_app - fileNameImpF: {fileNameImpF}')
        logging.info(f'main_app - fileNameDest: {fileNameDest}')

        main_app_Data()

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

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

    return


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

    Excel Import-Dateien zu Excel Ausw. übertragen
    """
    tStart = time()  # todo: Zeitmessung

    DEBUG = 1

    # ## === Variables Global anlegen

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

    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_3_excel_to_Ausw_Log_')
    logger_Settings()

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

    pass

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

    pass

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

    logger_Off()

    return


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

    """
    # ## === Variables Global anlegen
    pass

    debug_main = True
    main()

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


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