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

__all__ = ('WikiTempl', 'WikiDirTempl')

import os, re
from os import path

from ulib.base.uio import _s
from ulib.base.lines import Lines
from ulib.base.files import TextFile
from ulib.base.output import etitle, estep, eend
from base import Templ, FileTempl, register_templates

class WikiTempl(FileTempl):
    TEMPLATE = ('wiki file', 'wiki', 'w')
    FILENAME = ('Main', 'WelcomePage')
    EXT = '.wiki'

    RE_WIKI = re.compile('/wiki/')
    def MATCHES(cls, file):
        return cls.RE_WIKI.search(file) is not None
    MATCHES = classmethod(MATCHES)

    MODE = u"emacs-wiki"

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

    def update(self):
        if self.file is None:
            raise ValueError("file must be set")
        self.fix_properties()

        # XXX dans quel coding est enregistré le fichier?
        clines = Lines(self.gettext(self.CODING))
        coding = _s(clines[0])

        tf = TextFile(self.file)
        update = True
        for line in tf.lines[:5]:
            if line == coding:
                update = False
                break
        if update:
            tf.lines[0:0] = clines
            tf.writelines()

class WikiDirTempl(Templ):
    TEMPLATE = ('wiki directory', 'wikidir', 'wd')
    FILENAME = 'wiki'

    def create(self):
        if self.file is None:
            raise ValueError("file must be set")

        def mkdir():
            os.mkdir(self.file)

        etitle(self.file)
        try:
            estep(u"Création du répertoire de wiki", mkdir)

            main = path.join(self.file, 'Main')
            WikiTempl(main, **self.get_properties('nl', 'encoding')).create()
        finally:
            eend()

register_templates(WikiTempl, WikiDirTempl)
