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

__all__ = ('register_templates', 'get_registered_names', 'get_templ',
           'CannotOverwriteError', 'UpdateNotSupportedError',
           )

from os import path

from ulib.base.base import isseq

import pytempl, javatempl, wotempl
import texttempl, htmltempl, wikitempl, markdowntempl
import shtempl
from emptytempl import EmptyTempl # doit être en dernier
from base import register_templates, get_registered_names, TEMPL_REGISTRY, CannotOverwriteError, UpdateNotSupportedError

def find_templ_cls(file, template):
    if file is not None:
        file = path.abspath(file)
        _, filename = path.split(file)
        _, ext = path.splitext(filename)

    if template is not None:
        for templ_cls in TEMPL_REGISTRY:
            cls_templates = templ_cls.TEMPLATE
            if cls_templates is not None:
                if not isseq(cls_templates): cls_templates = (cls_templates,)
                if template in cls_templates:
                    return templ_cls
        raise ValueError("Invalid template name: %s" % template)
    if filename is not None:
        for templ_cls in TEMPL_REGISTRY:
            cls_filenames = templ_cls.FILENAME
            if cls_filenames is not None:
                if not isseq(cls_filenames): cls_filenames = (cls_filenames,)
                if filename in cls_filenames:
                    return templ_cls
    if ext is not None:
        for templ_cls in TEMPL_REGISTRY:
            cls_exts = templ_cls.EXT
            if cls_exts is not None:
                if not isseq(cls_exts): cls_exts = (cls_exts,)
                if ext in cls_exts:
                    return templ_cls
    # Si aucune des méthodes ci-dessus ne permet de trouver un template, en
    # chercher un qui se base sur le chemin vers le fichier à générer.
    for templ_cls in TEMPL_REGISTRY:
        if templ_cls.MATCHES(file):
            return templ_cls
    return EmptyTempl

def get_templ(file, template=None, **kw):
    templ_cls = find_templ_cls(file, template)
    return templ_cls(file, **kw)
