import plac
import subprocess
import config
import re

cfg = config.Config()
models_dir = cfg.portal_dir + "\\System\\Models"
cube_out = cfg.portal_dir + "\\System\\Cube_out"
cube_temp = cube_out + "\\temp"


@plac.pos('model_file', '', type=str)
def create(model_file):
    cube = cube_name(model_file)

    cmd = f'"{cfg.cognos_dir}\\runmac32.exe" "{cfg.tools_dir}\\VBS\\create-cube.mac" "{models_dir}","{model_file}","{cube_temp}"'
    print(f"Erstelle Cube '{cube}' fuer '{model_file}'...", end='')

    p = subprocess.Popen(cmd)
    p.wait()
    temp_file = f'{cube_temp}\\{model_file}.mdc'
    cube_file = f'{cube_out}\\{cube}.mdc'

    print('erfolgreich.')


def cube_name(model_file):
    p = re.compile(r'cube_out\\([^\.]+)\.mdc', re.IGNORECASE)
    with open(models_dir + '\\' + model_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(create)
