"""

"""

import argparse
import json
import logging
import os

import neoteric
from neoteric.util import log
from neoteric.util.unix import check_root
from neoteric.facts import network

__all__ = ["CliArgs", "CliArgsError"]

class CliArgsError(Exception):
    pass

class CliArgs(argparse.ArgumentParser):
    def __init__(self, *args, **kwargs):
        self.log_levels = {'debug': logging.DEBUG, 'info': logging.INFO}
        argparse.ArgumentParser.__init__(self, *args, **kwargs)
        self.add_argument(
            '-d', '--dry-run', dest='dry_run', action='store_true',
            help='Do not perform any actions, only log')
        self.add_argument(
            '-f', '--log-file', dest='log', default=None, type=str,
            help='Write to this log file in addition to stdout')
        self.add_argument(
            '-j', '--json-log', dest='json_log', default=None, type=str,
            help='Write JSON-formatted log lines to this log file '
            'in addition to stdout')
        self.add_argument(
            '-v', '--log-level', dest='log_level', default='debug', type=str,
            help='Use this log level {0}'.format(list(self.log_levels)))
        self.add_argument(
            '--fqdn', dest='fqdn', default=None, type=str,
            help='Override the detected fqdn with this value '
            '(applies globally by overriding neoteric.facts.network.FQDN)')
        self.add_argument(
            '--role', dest='role', default=None, type=str,
            help='Override FQDN matching and specify the the server role '
            'to apply.  --role has precedence over --fqdn.  '
            'The format is module.submodule.class')
        self.add_argument(
            '--hdata', dest='hdata', default=None, type=str,
            help='The path to a file containing HData to use')
        self.add_argument(
            '--remove', dest='remove', action='store_true',
            help='Uninstall the configuration for this server.')

    def parse_args(self, *args, **kwargs):
        result = argparse.ArgumentParser.parse_args(self, *args, **kwargs)
        self._check_hdata(result.hdata)
        if result.log_level not in self.log_levels:
            msg = "{0} is not a valid log level:  {1}".format(
                result.log_level, list(self.log_levels))
            logging.error(msg)
            raise CliArgsError(msg)
        if not result.dry_run and not check_root():
            msg = "You must run as root if not using --dry-run"
            logging.error(msg)
            raise CliArgsError(msg)
        neoteric.set_dry_run(result.dry_run)
        if result.fqdn:
            network.FQDN = result.fqdn
        log_level = self.log_levels[result.log_level]
        log.setup(result.log, result.json_log, log_level=log_level)
        return result

    def _check_hdata(self, path):
        if path is None:
            return
        if not os.path.isfile(path):
            raise CliArgsError("'{0}' does not exist".format(path))
        with open(path) as f:
            json.load(f) #check that it is valid JSON


