import plac
import subprocess
import re
from pathlib import Path
from datetime import datetime
import config

cfg = config.Config()
imr_dir = cfg.system_dir + '\\IQD'
catalog_dir = cfg.system_dir + '\\Catalogs'

export_translation = {
    'csv': 'x_ascii.flt',
    'xls': 'x_excel.flt',
    'sql': 'x_sql.flt',
    'txt': 'x_text.flt',
    'iqd': 'x_iqd.flt',
    'ims': 'ims'
}
min_filesize = 2000   # 1 kB


@plac.pos('imr_file', '', type=str)
@plac.opt('export_format', '', type=str, choices=export_translation.keys())
@plac.opt('export_dir', '', type=str)
@plac.opt('catalog', '', type=str)
def export(imr_file, export_format='csv', export_dir=None, catalog=None):
    imr_full_filename = imr_dir + '\\' + imr_file
    export_filename = Path(imr_full_filename).name[:-3] + export_format
    if export_dir is None:
        export_dir = str(Path(imr_full_filename).parent)
    export_full_filename = f'{export_dir}\\{export_filename}'
    if catalog is None:
        catalog = catalog_name(imr_file)
    if catalog[-4:] != '.cat':
        catalog = catalog + '.cat'
    catalog_full_filename = f'{catalog_dir}\\{catalog}'
    start = datetime.now().timestamp()
    cmd = f'"{cfg.cognos_dir}\\runmac32.exe" "{cfg.tools_dir}\\VBS\\impromptu.mac" "{imr_full_filename}","{catalog_full_filename}","{export_full_filename}","{export_translation[export_format]}"'
    print(f"Exportiere '{imr_file}' als '{export_format}' nach '{export_dir}'...", end='')

    p = subprocess.Popen(cmd)
    p.wait()
    if Path(export_full_filename).exists():
        export_stat = Path(export_full_filename).stat()
        if export_stat.st_mtime > start and export_stat.st_size > min_filesize:
            print('erfolgreich.')
            filesize_kb = round(export_stat.st_size / 1024)
            stop = datetime.now().timestamp()
            delta = round((stop - start))
            print(str(filesize_kb) + ' KB in ' + str(delta // 60) + ':' + str(delta % 60).zfill(2) + ' min geschrieben.')
            return
    print('fehlgeschlagen.')


def catalog_name(imr_file):
    p = re.compile(r'catalogs\\([^\.]+)\.cat', re.IGNORECASE)
    with open(imr_dir + '\\' + imr_file, 'r', errors='ignore') as f:
        for line in f.readlines():
            m = p.search(line)
            if m:
                return p.match(m.group()).groups()[0].lower()


if __name__ == '__main__':
    # plac.call(export)
    export('Belege\\current_date_Prognose.imr', 'ims')
