#!/usr/bin/env python
# coding: utf-8

import sys
import datetime
import terminal
from terminal.builtin import Command, log

from init import cli, info

url = 'https://github.com/init-template'
help_footer = '\n'.join([
    '  %s' % terminal.cyan('Examples:'),
    '',
    '    $ init python',
    '    $ init init-template/python',
    '',
    '  Find templates on %s' % terminal.underline(url),
])


program = Command(
    'init',
    description='init a project',
    version=info.VERSION,
    help_footer=help_footer,
)


def show_templates():
    ret = cli.templates()
    print('\n'.join(ret))
    sys.exit(0)

program.option('-l, --list', 'show available templates', action=show_templates)
program.add_log_options()


@program.action
def license(year=None, organization=None):
    """
    show available licenses.

    :param year: the copyright year
    :param organization: the organization name of the project

    :option organization: --organization [name]
    """

    from init import license

    args = filter(lambda o: not o.startswith('-'), program.args)

    if not year:
        year = datetime.datetime.utcnow().year

    if year:
        year = int(year)

    if args:
        name = args[0]
        data = license.parse(
            name,
            year=year,
            organization=organization,
        )
        if not data:
            print('Not Found')
            return
        sys.stdout.write(data)
    else:
        print('\t'.join(license.licenses()))
    return sys.exit()


@program.action
def install():
    """
    install a template to ~/.init-template/
    """
    if not program.args:
        return log.error('missing arguments')
    name = program.args[0]
    return cli.install(name)


@program.action
def update():
    """
    update templates in ~/.init-template/
    """
    if program.args:
        names = program.args
    else:
        names = cli.templates()
    for name in names:
        log.info('update', terminal.cyan(name))
        try:
            cli.install(name)
        except RuntimeError as e:
            log.error(e)

    sys.exit(0)


try:
    program.parse()
except RuntimeError as e:
    print('\n  %s\n' % e)
    sys.exit(1)

if not program.args:
    program.print_help()
    sys.exit(0)
else:
    cli.init(program.args[0])
