import plac
import subprocess
import pandas as pd
import time
from datetime import datetime
from pathlib import Path
from shutil import copy2
import config

cfg = config.config()
report_dir = cfg.portal_dir + '\\System\\Report'
publish_dir = cfg.portal_dir + '\\daten'


@plac.pos('config_file', '', type=str)
def portal(config_file='GAPS_neu'):
    print(f"== Portal '{config_file}.xml' ==")
    full_filename = f'{cfg.xml_dir}\\{config_file}.xml'
    if not Path(full_filename).exists():
        print(f"!! Datei '{full_filename}' existiert nicht !!")
        return
    prepare_report_temp(config_file)
    pub_dir = Path(f'{publish_dir}\\{config_file}')
    if not pub_dir.exists():
        pub_dir.mkdir()

    with open(f'{cfg.log_dir}\\{config_file}.mac.log', 'w') as logfile:
        export_files('jpg', pub_dir, logfile)
        export_files('xls', pub_dir, logfile)
        export_files('pdf', pub_dir, logfile)


def export_files(export_format, pub_dir, logfile):
    rep_dir = f'{report_dir}\\{export_format}'
    cmd = f'"{cfg.cognos_dir}\\runmac32.exe" "{cfg.tools_dir}\\publish-reports.mac" "{rep_dir}","{export_format}","{pub_dir}"'
    print(f"Exportiere '{rep_dir}' nach '{pub_dir}'...")
    start = datetime.now().timestamp()
    p = subprocess.Popen(cmd, stdout=logfile, stderr=logfile)
    reports = sorted(Path(rep_dir).glob('*.pp[rx]'))
    exports = [translate_filename(f.name, export_format, str(pub_dir)) for f in reports]
    exports_remaining = exports

    while p.poll() is None:
        exports_remaining = [f for f in exports_remaining if not f.exists() or f.stat().st_mtime < start]
        print('Fortschritt: ' + str(len(exports) - len(exports_remaining)) + '/' + str(len(exports)) + '...', end='\r')
        time.sleep(5)

    print('Abgeschlossen.             ')

    if export_format == 'jpg':
        rename_files(pub_dir)
        cleanup_dir(pub_dir)


def translate_filename(filename, export_format, pub_dir):
    if export_format == 'jpg':
        return Path(pub_dir + '\\' + filename[:-4] + 'graph1.jpg')
    return Path(pub_dir + '\\' + filename[:-4] + '_0.' + export_format)


def rename_files(pub_dir):
    for f in pub_dir.glob('*.jpg'):
        if f.exists():
            new_name = str(f).replace('graph', '_')
            f.replace(Path(new_name))


def cleanup_dir(pub_dir):
    for f in pub_dir.glob('*.htm'):
        f.unlink()


def prepare_report_temp(config_file):
    df = pd.read_csv(cfg.xml_dir + '\\info\\reports.csv', sep=';')
    df = df[df['Datei'].str.contains(config_file + '\\.', case=False)]
    format_list = [('GIF', 'jpg'), ('PDF', 'pdf'), ('XLS', 'xls')]

    for (filter_col, export_format) in format_list:
        reports = set(df[df[filter_col] == 'J']['Report'].to_list())
        rep_dir = f'{report_dir}\\{config_file}\\{export_format}'
        unlink_and_recreate(Path(rep_dir))

        for rep in reports:
            ppx = report_dir + '\\' + rep + '.ppx'
            ppr = report_dir + '\\' + rep + '.ppr'
            if Path(ppx).exists():
                copy2(ppx, rep_dir)
            elif Path(ppr).exists():
                copy2(ppr, rep_dir)


def unlink_and_recreate(dirname):
    if not dirname.exists():
        dirname.mkdir(parents=True)
    else:
        for f in dirname.glob('*.pp[xr]'):
            f.unlink()


if __name__ == '__main__':
    plac.call(portal)
