#! /usr/bin/env python2
# -*- coding: utf-8 -*-
# PYTHON_ARGCOMPLETE_OK

import argtoolbox
import os
import sys
import argparse
import importlib
import logging


class ConfigGenerationCommand(object):
    """TODO"""

    def __call__(self, args):
        glog.debug("args : " + str(args))
        if args.debug:
            glog.setLevel(logging.DEBUG)
        config = self.getconfig(args)
        self.generate(args, config)

    def getconfig(self, args):
        glog.info("Looking for Config object into input program ...")
        glog.debug("input program name : '" + str(args.program) +"'")
        program = args.program
        local_dir = os.path.dirname(program)
        glog.debug("local_dir : '" + str(local_dir) +"'")
        sys.path.append(local_dir)

        module_name = program.split('/')[-1].split('.')[0]
        glog.debug("module name found : " + str(module_name))

        level = logging.getLogger().getEffectiveLevel()
        module = importlib.import_module(module_name)
        glog.setLevel(level)

        result = None
        for i in dir(module):
            temp_class = getattr(module, i)
            if isinstance(temp_class, argtoolbox.Config):
                glog.debug("variable name found : " + str(i))
                glog.debug("variable type found : " + str(type(temp_class)))
                result = temp_class
                break
            elif isinstance(temp_class, argtoolbox.BasicProgram) or  isinstance(temp_class, argtoolbox.DefaultProgram):
                glog.debug("variable name found : " + str(i))
                glog.debug("variable type found : " + str(type(temp_class)))
                result = temp_class.config
                break
        if result :
            glog.info("Config object found : " + result.prog_name)
        return result

        
    def generate(self, args, config):
        glog.info("Trying to generate the default configuration file ...")
        configfile = os.path.expanduser('~/.' + config.prog_name + '.cfg')
        glog.info("The default configuration file name is : " + configfile)
        if args.output:
            configfile = args.output
            if configfile[:-4] != ".conf":
                configfile += ".conf"
            glog.warn("Using '" + configfile + "' as configuration file name.")

        if not args.force_yes:
            if os.path.exists(configfile):
                glog.warn("The current file already exists : " + str(configfile))
                if not argtoolbox.query_yes_no("Overwrite ?", "no"):
                    glog.error("Aborted.")
                    return False
        config.write_default_config_file(configfile, args.nocomments)
        glog.info("Done.")




# -----------------------------------------------------------------------------
# MAIN
# -----------------------------------------------------------------------------
# logger
glog = logging.getLogger()
glog.setLevel(logging.INFO)
# logger handlers
glog.addHandler(argtoolbox.streamHandler)


myparser = argparse.ArgumentParser()
myparser.add_argument('-d', dest="debug", action="count", help="Debug")
myparser.add_argument('-v', '--verbose', action="store_true", default=False)
myparser.add_argument('--version', action="version", version="%(prog)s 0.1")

subparsers = myparser.add_subparsers()

parser_tmp = subparsers.add_parser(
    'generate',
    help="generate the default pref file")
parser_tmp.add_argument('--output', action="store")
parser_tmp.add_argument('--intput', action="store", dest="program", required=True)
parser_tmp.add_argument(
    '-n',
    dest="nocomments",
    action="store_false",
    help="config file generation without commments.")
parser_tmp.add_argument(
    '-f',
    dest="force_yes",
    action="store_true",
    help="overwrite the current output file even it still exists.")
parser_tmp.set_defaults(__func__=ConfigGenerationCommand())


PROG = argtoolbox.DefaultProgram(myparser)
if __name__ == "__main__":
    if PROG():
        sys.exit(0)
    else:
        sys.exit(1)
