import os
import sys


class AppBase:
    def __init__(self, cls, argv=None, **options):
        """The base template class.

        This class encapsulates the logic to run users' app or print help
        message. If your template is not like this, just don't inherit from
        this class. However, to provide a consistent API for end users, you
        should create a class with the same arguments in __init__ function as
        AppBase.

        Arguments:
            cls:        the target object
            argv:       if not provided, use sys.argv as the argument list
            options:    control the behavior of the template class
        """
        if argv:
            if not getattr(self, 'app_name', ''):
                self.app_name = 'APP_NAME'
        else:
            argv = sys.argv
            self.app_name = os.path.basename(argv[0])
            argv = argv[1:]

        if options.get('noop') is True:
            return

        if '-h' in argv or '--help' in argv:
            self.help(cls, argv, **options)
            exit()

        self.result = self.run(cls, argv, **options)

    def run(self, cls, argv, **options):
        """
        Arguments:
            cls:        the target object
            argv:       if not provided, use sys.argv as the argument list
            options:    control the behavior of the template class
        """
        raise NotImplementedError('This template doesn\'t implement "run" function.')

    def help(self, cls, argv, **options):
        """
        Arguments:
            cls:        the target object
            argv:       if not provided, use sys.argv as the argument list
            options:    control the behavior of the template class
        """
        raise NotImplementedError('This template doesn\'t implement "help" function.')

    @staticmethod
    def eprint(*args, **kwargs):
        """
        Redirect the message to sys.stderr
        """
        print(*args, file=sys.stderr, **kwargs)
