#!/usr/bin/env python
# -*- coding: utf-8 -*- vim:sw=4:sts=4:et:ai:si:sta:fenc=utf-8

import os, sys, re
from os import path

from ulib.all import *
from ulib.p.templ import *

def new_cmd(*args):
    """
    @return: le status d'exécution de la commande.
    @rtype: Status
    """
    class NewOptions(Options):
        def __init__(self):
            super(NewOptions, self).__init__()
            self.add_option('+')
            self.add_option('--help', Options.SetValue(True))
            self.add_option(('--template=', '-t:'), Options.SetValue())
            self.add_option(('--edit', '-e'), Options.SetValue(True, initial=True))
            self.add_option(('--noedit', '-n'), Options.SetValue(False, 'edit'))
            # Options standards de Templ et FileTempl
            self.add_option('--nl=', Options.SetValue())
            self.add_option(('--overwrite', '-f'), Options.SetValue(True))
            self.add_option(('--encoding=', '--enc=', '-E:'), Options.SetValue())
            self.add_option(('--executable', '--exec', '-x'), Options.SetValue(True))
            self.add_option(('--noexec', '-n'), Options.SetValue(False, 'executable'))

    options = NewOptions()
    optvalues, args = options.parse(args)

    if options.help:
        print "XXX help"
        return OK_STATUS

    if not args:
        eerror(u"Vous devez spécifier le fichier à créer")
        return ERROR_STATUS

    file, args = args[0], args[1:]
    templ = get_templ(file, options.template)
    estep(u"Sélection du modèle %s" % seqof(templ.NAME)[0])

    status = OK_STATUS
    try:
        # parser la ligne de commande
        templ.parse_args(args)
        # ajouter les options spécifiées ici
        for name in ('nl', 'overwrite', 'encoding', 'executable'):
            if options.was_parsed(name):
                value = options.get_value(name)
                templ.set_property(name, value)
        # puis créer le fichier
        templ.create()
    except CannotOverwriteError:
        eerror(u"Refus d'écraser le fichier cible (utiliser -f)")
        status = ERROR_STATUS
    except IOError:
        eerror()
        status = ERROR_STATUS

    if status == OK_STATUS and options.edit and templ.editable is not None:
        file = templ.editable
        etitle(u"Edition de %s" % _u(file))
        if ask_yesno(u"Voulez-vous éditer %s?" % _u(file), True, I_INTER):
            status = edit_file(file)

    return status

def run_uproject():
    args = sys.argv[1:]

    cmd_name = args[0:1] and args[0] or None
    if cmd_name is None: die("La commande est requise")
    args = args[1:]

    cmd = {'new': new_cmd,
           }.get(cmd_name, None)
    if cmd is None: die(u"Commande invalide: %s" % cmd_name)

    try:
        exit(cmd(*args))
    except Exit: raise
    except: die()

if __name__ == '__main__':
    run_uproject()
