#!/usr/bin/env python3

"""
    ircd.configure
    ~~~~~~~~~~~~~~

    Command-line configuration script for XinIRCd.
"""

import yaml

from ircd.constants import *

OPTIONS = {}

DEFAULTS = {
    "MODULE_DIR": os.path.abspath(
        os.path.dirname(__file__) + os.sep + "modules"),
    "MAX_CLIENT": 1024,
    "NICK_LENGTH": 32,
    "CHAN_LENGTH": 64,
    "MAX_CHANNEL": 20,
    "MOTD_FILE": os.path.abspath("motd.txt"),
    "PORTS": ["6667"]
}


def getopt(key, default=None):
    return OPTIONS.get(key, default)


def setopt(key, value, persist=False):
    OPTIONS[key] = value
    if persist:
        # TODO persist
        pass


def read_config():
    global OPTIONS
    OPTIONS = yaml.load(open(CONFIG_FILE, "r"))
    # TODO config validation
    # TODO make sure bind is a list of host/port pairs


def configure():
    conf = dict(DEFAULTS.items())

    print(YELLOW + "Welcome to the XinIRCd Configuration!" + NORMAL)
    print()

    print("In what directory should the modules loaded from?")
    conf["MODULE_DIR"] = input("~ [" + GREEN + DEFAULTS["MODULE_DIR"] + NORMAL
                               + "] ") or DEFAULTS["MODULE_DIR"]
    print()

    if not os.path.exists(conf["MODULE_DIR"]):
        print("The module directory doesn't exist. Create it? (y/n)")
        if input("~ [" + GREEN + "y" + NORMAL + "] ").lower() != "n":
            os.makedirs(conf["MODULE_DIR"])
        print()

    print("Server name? (required for SSL, put FQDN)")
    conf["SERVER_NAME"] = input("~ ")
    print()

    while not conf["SERVER_NAME"]:
        print(RED + "Please enter a valid server name." + NORMAL)
        conf["SERVER_NAME"] = input("~ ")
        print()

    print("Maximum number of clients at any time? (" + GREEN +
          "1-" + str(DEFAULTS["MAX_CLIENT"]) + NORMAL + ")")
    conf["MAX_CLIENT"] = input(
        "~ [" + GREEN + str(DEFAULTS["MAX_CLIENT"]) + NORMAL + "] ") or \
                         str(DEFAULTS["MAX_CLIENT"])
    print()

    while not conf["MAX_CLIENT"].isdigit() or int(conf["MAX_CLIENT"]) > \
        DEFAULTS["MAX_CLIENT"]:
        print(RED + "Please enter a valid number between " +
              GREEN + "1-" + str(DEFAULTS["MAX_CLIENT"]) + NORMAL)
        conf["MAX_CLIENT"] = input(
            "~ [" + GREEN + str(DEFAULTS["MAX_CLIENT"]) + NORMAL + "] ") or \
                             str(DEFAULTS["MAX_CLIENT"])
        print()
    conf["MAX_CLIENT"] = int(conf["MAX_CLIENT"])

    print("Maximum length of nicknames?")
    conf["NICK_LENGTH"] = input(
        "~ [" + GREEN + str(DEFAULTS["NICK_LENGTH"]) + NORMAL + "] ") or \
                          str(DEFAULTS["NICK_LENGTH"])
    conf["NICK_LENGTH"] = int(conf["NICK_LENGTH"])
    print()

    print("Maximum length of channel names?")
    conf["CHAN_LENGTH"] = input(
        "~ [" + GREEN + str(DEFAULTS["CHAN_LENGTH"]) + NORMAL + "] ") or \
                          str(DEFAULTS["CHAN_LENGTH"])
    conf["CHAN_LENGTH"] = int(conf["CHAN_LENGTH"])
    print()

    print("Maximum number of channels a user can join?")
    conf["MAX_CHANNEL"] = input(
        "~ [" + GREEN + str(DEFAULTS["MAX_CHANNEL"]) + NORMAL + "] ") or \
                          str(DEFAULTS["MAX_CHANNEL"])
    conf["MAX_CHANNEL"] = int(conf["MAX_CHANNEL"])
    print()

    with open(CONFIG_FILE, "w") as out:
        yaml.dump(conf, out, default_flow_style=False)
    print("DONE!")
    print("*** " + CYAN + "Remember to edit your configuration files!" +
          NORMAL + " ***")
    print()


if __name__ == "__main__":
    configure()
