#!/usr/bin/env python3
import argparse
from configparser import ConfigParser
import io
import sys
# import the code from this package
from shell_command_logger.config import load_config, SclConfig, DEFAULT_CONFIG, CONFIG_PATH


def config_to_parser(scl_config: SclConfig) -> str:
    parser = ConfigParser()
    parser["Output"] = {
        "DataDirectory": scl_config.output_dir,
        "AddReadmeFile": scl_config.add_readme,
    }
    parser["Replay"] = {
        "CommandFormat": scl_config.command_format,
        "ReplaySpeed": scl_config.replay_speed,
    }
    return parser


def parser_to_text(parser: ConfigParser) -> str:
    fake_file = io.StringIO()
    parser.write(fake_file)
    return fake_file.getvalue()


def save_parser_as_config(parser: ConfigParser) -> None:
    path = CONFIG_PATH.saveFilePath(mkdir=True)
    with open(path, "w") as f:
        parser.write(f)
    print(f"Wrote config to '{path}':")
    print(parser_to_text(parser).rstrip())


def main() -> None:
    ap = argparse.ArgumentParser()
    group = ap.add_mutually_exclusive_group()
    group.add_argument("-d", "--defaults", action="store_true", help="reset all settings back to the defaults")
    group.add_argument("-s", "--set", metavar=("<section>", "<key>", "<new_value>"), nargs=3, help="set an option: <section>.<key> = <new_value>")
    group.add_argument("-p", "--print", action="store_true", help="print the current config")
    args = ap.parse_args()

    scl_config = load_config()
    if args.print:
        parser = config_to_parser(scl_config)
        text = parser_to_text(parser)
        print(text.rstrip())
    elif args.set:
        section, key, new_value = args.set
        parser = config_to_parser(scl_config)
        parser[section][key] = new_value
        save_parser_as_config(parser)
    elif args.defaults:
        parser = config_to_parser(DEFAULT_CONFIG)
        save_parser_as_config(parser)
    else:
        ap.print_help()


if __name__ == "__main__":
    main()
