"""
CLI commands
"""
import sys
import os


API = ('"""\n'
       'generated by restae-admin\n'
       '\n'
       '{module_name_cap} module\n'
       '"""\n'
       '\n'
       'from restae.handlers import APIModelHandler\n'
       'from model import {module_name_cap}, {module_name_cap}Serializer\n'
       '\n'
       '\n'
       'class {module_name_cap}Handler(APIModelHandler):\n'
       '    """\n'
       '    {module_name_cap} Handler\n'
       '    """\n'
       '    queryset = {module_name_cap}.query()\n'
       '    serializer_class = {module_name_cap}Serializer\n'
       '\n')

MODEL = ('"""\n'
         'generated by restae-admin\n'
         '\n'
         '{module_name_cap} models and serializers\n'
         '"""\n'
         '\n'
         'from google.appengine.ext import ndb\n'
         'from restae.serializers import ModelSerializer\n'
         '\n'
         '\n'
         'class {module_name_cap}(ndb.Model):\n'
         '    """\n'
         '    {module_name_cap} models class\n'
         '    """\n'
         '    pass\n'
         '\n'
         '\n'
         'class {module_name_cap}Serializer(ModelSerializer):\n'
         '    """\n'
         '    {module_name_cap} serializer\n'
         '    """\n'
         '    class Meta:\n'
         '        fields = \'__all__\'\n'
         '\n')


def generate(args):
    if args[0] == 'module':
        module_name = args[1]

        try:
            os.mkdir(module_name)
        except OSError:
            pass

        with open(os.path.join(module_name, '__init__.py'), 'w+') as ifile:
            ifile.write('# generated by restae-admin\n')

        with open(os.path.join(module_name, 'api.py'), 'w+') as ifile:
            ifile.write(API.format(
                module_name=module_name,
                module_name_cap=module_name.capitalize()
            ))

        with open(os.path.join(module_name, 'model.py'), 'w+') as ifile:
            ifile.write(MODEL.format(
                module_name=module_name,
                module_name_cap=module_name.capitalize()
            ))
        print 'Module ' + module_name + ' created !'


def execute_from_command_line(argv=None):
    args = argv or sys.argv
    args = args[1:]

    if args and len(args) == 3 and args[0] == 'g':
        generate(args[1:])
