# coding: utf-8

from __future__ import print_function, absolute_import, division, unicode_literals

import sys
import os  # NOQA

from ruamel.std.argparse import (
    ProgramBase,
    option,
    CountAction,
    SmartFormatter,
    sub_parser,
    version,
)
from ruamel.appconfig import AppConfig
from . import __version__, _package_data
from .data import Data


def to_stdout(*args):
    sys.stdout.write(' '.join(args))


class DataCmd(ProgramBase):
    def __init__(self):
        super(DataCmd, self).__init__(
            formatter_class=SmartFormatter,
            # aliases=True,
            # usage="""""",  # auto generated
            # description="""""",  # before options in help
            # epilog="""""",  # after options in help
            full_package_name=_package_data['full_package_name'],
        )

    # you can put these on __init__, but subclassing DataCmd
    # will cause that to break
    # mt: off
    @option(
        '--verbose',
        '-v',
        help='increase verbosity level',
        action=CountAction,
        const=1,
        nargs=0,
        default=0,
        global_option=True,
    )
    # mt: on
    @version('version: ' + __version__)
    def _pb_init(self):
        # special name for which attribs are included in help
        pass

    def run(self):
        self.data = Data(self._args, self._config)
        if hasattr(self._args, 'func'):  # not there if subparser selected
            return self._args.func()
        self._parse_args(['--help'])  # replace if you use not subparsers

    def parse_args(self):
        self._config = AppConfig(
            'ruamel_yaml_data',
            filename=AppConfig.check,
            parser=self._parser,  # sets --config option
            warning=to_stdout,
            add_save=False,  # add a --save-defaults (to config) option
        )
        # self._config._file_name can be handed to objects that need
        # to get other information from the configuration directory
        self._config.set_defaults()
        self._parse_args(
            # default_sub_parser="",
        )

    @sub_parser(help='some command specific help')
    # @option('--session-name', default='abc')
    def show(self):
        # self.redirect()
        pass

    def redirect(self, *args, **kw):
        """
        redirect to a method on self.develop, with the same name as the
        method name of calling method
        """
        getattr(self.data, sys._getframe(1).f_code.co_name)(*args, **kw)


def main():
    n = DataCmd()
    n.parse_args()
    sys.exit(n.run())


if __name__ == '__main__':
    main()
