# -*- coding: utf-8 -*- vim:sw=4:sts=4:et:ai:si:sta:fenc=utf-8
import ulib.base.i_need_py23

__all__ = ('PyTempl', 'PyModuleTempl')

import os
from os import path

from ulib.base.uio import _u
from ulib.base.lines import Lines
from ulib.base.input import is_yes
from ulib.base.output import etitle, ebegin, eend, estep, eerror
from base import Templ, FileTempl, register_templ, CannotOverwriteError

class PyTempl(FileTempl):
    NAME = ('pyfile', 'pyf', 'python', 'py')
    EXT = ('.py', '.pyw')

    _executable = True
    pyulib = True

    PROPERTIES, ALIASES, OPTIONS = \
        FileTempl.DECL_P(FileTempl, 'executable', 'noexec', 'pyulib', 'nopyulib',
                         executable=dict(initial=_executable, value=True, aliases=('exec', 'x')),
                         noexec=dict(varname='executable', value=False, aliases='n'),
                         pyulib=dict(initial=pyulib, value=True),
                         nopyulib=dict(varname='pyulib', value=False, aliases='c'),
                         )

    MODE = u"python"

    SHEBANG = u"""#!/usr/bin/env python"""
    DOC = u'''\
u"""%%(scriptname)s:

USAGE
    %%(scriptname)s [options]"""
'''
    TRUEFALSE = u"""\
try: True, False
except: True, False = 1, 0
"""
    PYULIB = u"""\
import os, sys
from os import path

from ulib.all import *

def display_help():
    uprint(__doc__ %% globals())

def run_%(funcname)s():
    options, longoptions = build_options([
        ('h', 'help', "Afficher l'aide"),
        ])
    options, args = get_args(None, options, longoptions)
    for option, value in options:
        if option in ('-h', '--help'):
            display_help()
            sys.exit(0)

if __name__ == '__main__':
    run_%(funcname)s()
"""
    ALL = u"""\
__all__ = ()
"""

    def __fix_funcname(self, basename):
        # s'assurer que basename, le nom du fichier, peut-être utilisé comme nom
        # de fonction. pour le moment, on remplace seulement '-' par '_'
        return basename.replace('-', '_')

    funcname = None

    def get_lines(self):
        lines = Lines()
        modeline = self.get_modeline(nl=True)
        self.funcname = self.__fix_funcname(self.basename)
        if self.executable:
            self.appendtext(lines, self.SHEBANG)
            self.appendtext(lines, modeline)
            self.appendtext(lines, self.DOC)
            #self.appendtext(lines, self.TRUEFALSE)
            if self.pyulib:
                self.appendtext(lines, self.PYULIB)
        else:
            self.appendtext(lines, modeline)
            self.appendtext(lines, self.ALL)
            #self.appendtext(lines, self.TRUEFALSE)
        return lines

class PyModuleTempl(Templ):
    NAME = ('pymodule', 'pym')

    def mkdir(self):
        if not path.isdir(self.file):
            os.mkdir(self.file)

    def create(self):
        etitle(self.file)
        try:
            self._check_file()

            if not path.exists(self.file):
                estep(u"Création du répertoire")
                os.mkdir(self.file)
            elif not path.isdir(self.file):
                eerror(u"Un fichier du même nom existe: %s" % _u(self.file))
                raise CannotOverwriteError(self.file)

            initfile = path.join(self.file, '__init__.py')
            inittempl = PyTempl(initfile, **self.get_properties('nl', 'overwrite', 'encoding'))
            inittempl.executable = False
            inittempl.create()
            self.editable = initfile
        finally:
            eend()

register_templ(PyTempl, PyModuleTempl)
