#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import glob
import os
import argparse


def set_prophane_config_paths(
        prophane_base_dir, db_base_dir,
        job_base_dir, general_config_path="/path/to/general_config"
):
    mods = [
        ("/path/to/prophane", prophane_base_dir),
        ("/path/to/test_dbs", db_base_dir),
        ("/path/to/test_job", job_base_dir),
        ("/path/to/general_config", general_config_path)
    ]
    yamls = replace_yaml_paths(job_base_dir, mods)
    return yamls


def set_db_config_paths(db_base_dir):
    mods = [
        ("/path/to/test_dbs", db_base_dir)
    ]
    yamls = replace_yaml_paths(db_base_dir, mods)
    return yamls


def set_general_config_paths(general_cfg, db_base_dir):
    mods = [
        ("/path/to/test_dbs", db_base_dir)
    ]
    replace_strings_in_file(general_cfg, mods)
    return general_cfg


def set_dir(prophane_dir, test_base_dir=os.path.dirname(os.path.abspath(__file__))):
    prophane_base_dir = os.path.abspath(prophane_dir)
    db_base_dir = os.path.join(test_base_dir, "test_dbs")
    job_base_dir = os.path.join(test_base_dir, "test_job")
    set_db_config_paths(db_base_dir)
    set_prophane_config_paths(prophane_base_dir, db_base_dir, job_base_dir)
    set_general_config_paths(
        general_cfg=os.path.join(prophane_base_dir, 'general_config.yaml'),
        db_base_dir=db_base_dir
    )


def replace_yaml_paths(base_dir, mods):
    yamls = []
    for fname in glob.glob(str(base_dir) + "/**/*.yaml", recursive=True):
        yamls.append(fname)
        replace_strings_in_file(fname, mods)
    return yamls


def replace_strings_in_file(fname, mods):
    with open(fname, "r") as handle:
        content = handle.read()
        for m, n in mods:
            content = content.replace(m, n)
    with open(fname, "w") as handle:
        handle.write(content)
    print(fname, "adapted")


def parse_args():
    parser = argparse.ArgumentParser(description="setting up prophane's test database and job data")
    parser.add_argument('dir', type=str,
                        help='absolute path to your prophane installation')
    return parser.parse_args()


def main():
    args = parse_args()
    if not os.path.isdir(args.dir):
        exit("error: " + args.dir + " is not a valid directory")
    set_dir(args.dir)
    print("done")


if __name__ == "__main__":
    main()
