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

__all__ = ('PropertiesTempl', 'JavaTempl')

import os, re
from os import path

from ulib.base.base import isseq
from ulib.base.uio import _u
from ulib.base.encoding import LATIN1
from ulib.base.lines import Lines
from ulib.base.dates import datef
from base import FileTempl, register_templates

class PropertiesTempl(FileTempl):
    TEMPLATE = ('properties file', 'properties')
    FILENAME = ('Properties',)
    EXT = '.properties'

    VPS, ACPS, NCPS, ICPS = FileTempl.PS('-encoding')

    def fix_properties(self):
        FileTempl.fix_properties(self)
        self.encoding = LATIN1

    def get_lines(self):
        return self.appendtext(None, self.modeline)

RE_COMMA = re.compile(r"[\s,]*")

def imports_parser(values):
    if values:
        if not isseq(values):
            values = filter(None, RE_COMMA.split(values.strip()))
        return u"\n".join([u"import %s;" % value for value in values])
    return u""

def extends_parser(value):
    if value: return u" extends %s" % _u(value).strip()
    else: return u""

def implements_parser(values):
    if values:
        if not isseq(values):
            values = filter(None, RE_COMMA.split(values.strip()))
        if values: return " implements %s" % u", ".join(values)
    return u""

class JavaTempl(FileTempl):
    TEMPLATE = ('java file', 'java', 'j')
    EXT = '.java'

    VPS, ACPS, NCPS, ICPS = FileTempl.PS('package', 'imports', 'extends', 'implements',
                                         icps=dict(package=None,
                                                   imports=imports_parser,
                                                   extends=extends_parser,
                                                   implements=implements_parser))

    cdate = None
    package = None
    imports = None
    extends = None
    implements = None
    body = None

    RE_PACKAGE = re.compile(r'\s*package\s+(\S+)\s*;')

    def __init__(self, file, **properties):
        FileTempl.__init__(self, file, **properties)
        self.autodetect_package()

    def autodetect_package(self):
        # Essayer d'autodétecter le package à partir d'autres fichiers du même répertoire
        dir, _ = path.split(self.file)
        if not dir: dir = '.'
        if not path.isdir(dir): return False

        files = [file for file in os.listdir(dir) if file.endswith('.java')]
        if not files: return False

        lines = Lines().readlines(path.join(dir, files[0]))
        packages = lines.grep(self.RE_PACKAGE)
        if not packages: return False

        mo = self.RE_PACKAGE.match(packages[0])
        self.package = mo.group(1)
        return True

    def fix_properties(self):
        FileTempl.fix_properties(self)
        if self.cdate is None: self.cdate = datef()
        self.imports = self.imports or u""
        if isseq(self.imports): self.imports = imports_parser(self.imports)
        self.extends = self.extends or u""
        self.implements = self.implements or u""
        if isseq(self.implements): self.implements = implements_parser(self.implements)

    def set_imports(self, *imports):
        self.imports = imports_parser(imports)

    def set_extends(self, extends):
        self.extends = extends_parser(extends)

    def set_implements(self, *implements):
        self.implements = implements_parser(implements)

    #MODE = u"java"
    MODELINE_PREFIX = u"/* "

    PACKAGE = u"""package %(package)s;"""
    IMPORTS = u"""%(imports)s"""
    CLASS = u"""\
/**
 * @author jclain
 */
public class %(basename)s%(extends)s%(implements)s {"""

    def get_lines(self):
        lines = Lines()
        self.appendtext(lines, self.modeline)
        self.appendtext(lines, u"""\
 * %(filename)s
 * Créé le %(cdate)s
 */""")
        if self.package: self.appendtext(lines, self.PACKAGE)
        if self.imports:
            self.appendtext(lines, self.IMPORTS, bnl=True)
        self.appendtext(lines, self.CLASS, bnl=True)
        if self.body: self.appendtext(lines, self.body)
        self.appendtext(lines, u"}")
        return lines

register_templates(PropertiesTempl, JavaTempl)
