#!/usr/bin/env python
import argcomplete
import argparse
import json
import os
import sys
from os.path import expanduser

pathname = os.path.dirname(os.path.abspath(__file__))
GLOBAL_CONFIG_FILE = os.path.join(os.path.abspath(expanduser("~")), '.d-tool.config.json')
LOCAL_CONFIG_FILE = os.path.abspath(os.path.join(pathname, '.d-tool.config.json'))


def call(cmd, pwd=None):
    print cmd
    if pwd is None:
        pwd = os.path.abspath(os.path.join(pathname, ".."))
    os.chdir(pwd)
    res = os.system(cmd)
    if res != 0:
        print("error calling the script {}".format(res))
        exit(1)


def docker_compose_params():
    parts, project_name = read_config()
    result = ""
    for c in parts:
        result += "-f {} ".format(c)
    if project_name:
        result += "-p {} ".format(project_name)
    return result


def get_container_param(container):
    if container is None:
        container = get_last_container()
    container = container.replace(".Dockerfile", "")
    set_last_container(container)
    return container


def get_container():
    if len(sys.argv) != 2:
        raise Exception("container parameter is required")
    # todo: store last used container
    container = sys.argv[1] if len(sys.argv) == 2 else "dlp_c"
    container = container.replace(".Dockerfile", "")
    return container


def compose_project():
    _, project_name = read_config()
    if project_name is None:
        raise Exception("default project name is not supported") # todo fix me
    return project_name


def read_config():
    config_file = get_config_file()
    if config_file is None:
        print("Can't find config file, use dset command first.")
        exit(1)
    try:
        with open(config_file) as configfile:
            content = configfile.readlines()
            content = [str for str in content if not str.startswith("//")]
            data = json.loads("\n".join(content))
            return data['docker_compose_files'], data['project_name']
    except IOError:
        print "Can't open the config file, run ./dset command first"
        quit(1)


def get_config_file():
    if os.path.isfile(LOCAL_CONFIG_FILE):
        return LOCAL_CONFIG_FILE
    if os.path.isfile(GLOBAL_CONFIG_FILE):
        return GLOBAL_CONFIG_FILE
    return None


def update_config(config_file, docker_compose_files, project_name):
    docker_compose_files = list(set([os.path.abspath(dc_file) for dc_file in docker_compose_files]))
    for dc_file in docker_compose_files:
        if not os.path.exists(dc_file):
            print("File not found {}".format(dc_file))
            exit(1)
    data = {'docker_compose_files': docker_compose_files}
    try:
        current_compose_files, current_project_name = read_config()
    except:
        current_compose_files, current_project_name = [], ""
    data['project_name'] = project_name if project_name else current_project_name
    data['docker_compose_files'] = [f for f in data['docker_compose_files'] + current_compose_files if f not in current_compose_files or f not in data['docker_compose_files']]
    print("write to file {}".format(config_file))
    with open(config_file, 'w') as configfile:
        configfile.write(json.dumps(data))


if __name__ == '__main__':
    parser = argparse.ArgumentParser(description='Set docker-compose configuration. Print out current config if no parameters passed.')
    parser.add_argument("docker_compose_files", help="location of docker-compose files to be _toggled_ in d-tools config file", nargs='*')
    parser.add_argument("-p", "--project_name", help="specify project name for docker-compose")
    parser.add_argument("-g", "--global", help="use global configuration", dest='is_global', action='store_true')
    parser.set_defaults(is_global=False)
    argcomplete.autocomplete(parser)
    args = parser.parse_args()
    config_file = GLOBAL_CONFIG_FILE if args.is_global else LOCAL_CONFIG_FILE
    if len(args.docker_compose_files) == 0:
        print "Config file: {}".format(config_file)
        compose_files, project_name = read_config()
        print "Project name: {}".format(project_name)
        print "Compose files:\n{}".format("\n".join("  " + f for f in compose_files))
    else:
        update_config(config_file, args.docker_compose_files, args.project_name)
    # todo allow to modify existing config file. how? print out a command that creates current config file
