import subprocess
import time
from datetime import datetime
from pathlib import Path
import config

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


def portal(portal_file):
    print(f"== Portal '{portal_file}.xml' ==")
    full_filename = f'{cfg.xml_dir}\\{portal_file}.xml'
    if not Path(full_filename).exists():
        print(f"!! Datei '{full_filename}' existiert nicht !!")
        return
    prepare_report_temp()
    pub_dir = Path(f'{publish_dir}\\{portal_file}')
    if not pub_dir.exists():
        pub_dir.mkdir()

    with open(f'{cfg.log_dir}\\{portal_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():
    pass


if __name__ == '__main__':
    portal('GAPS_neu')
