# -*- coding: iso-8859-1 -*-
"""
    MoinMoin - ToDo Parser

    @copyright: 2007, 2008 Terry Brown <terry_n_brown@yahoo.com>
    @license: GNU GPL
    @version: 200803112319

"""

from MoinMoin.parser._ParserBase import ParserBase
from MoinMoin.parser import text_moin_wiki

Dependencies = []

class Parser (ParserBase):
    """
        Format todo items
    """

    parsername = "Todo"
    extensions = '*'
    Dependencies = []

    def __init__(self, raw, request, **kw):
        ParserBase.__init__(self, raw, request, **kw)
        self.form = request.form
        self._ = request.getText

    def format(self, formatter):
        """ Send the text. """

        _ = self._

        tmplt = (
            'title', 'Item', 'T', True, _('Task'),
            'percent', 0, '%', True, '%',
            'who', 'Unassigned', 'W', True, _('Who'),
            'due', '', 'D', False, _('Due'),
            'starts', '', 'S', False, _('Start'),
            'priority', '', 'P', False, _('Priority'),
            'units', '', 'U', False, _('Effort'),
            'description', '', 'E', False, _('Details'),
            )

        t = 5  # update this to match columns in data above
        flds = tmplt[0::t]  # ordered list of fields
        keys = dict(zip(tmplt[2::t], flds))  # map tag to field name
        showDefault = dict(zip(flds, tmplt[3::t]))
        # should column appear if no data supplied?
        headings = dict(zip(flds, tmplt[4::t]))  # map field name to headings

        tmplt = dict(zip(flds, tmplt[1::t]))  # default item

        present = set([k for k in showDefault.keys() if showDefault[k]])
        # fields with showDefault == True are always shown / present

        items = []

        for line in self.raw.split('\n'):

            if line.startswith('#'): continue  # a comment

            if line.startswith((' ','\t')) or line == '':  # extra material
                if items:
                    item = items[-1]
                    if 'log' not in item:
                        item['log'] = ''
                        x = 0  # strip same whitespace of all lines in block
                        while x < len(line) and line[x] in ' \t': x+=1
                    txt = line[x:].replace('<<<', '{{{')
                    txt = txt.replace('>>>', '}}}')
                    item['log'] = item['log'] + '\n' + txt
                continue

            tagMode = ':' in line.split('|')[0]

            if not tagMode:
                item = dict(zip(flds,
                    [i.strip() for i in line.split('|')]))
            else:
                item = {}
                for spec in line.split('|'):
                    k,v = [i.strip() for i in spec.split(':', 1)]
                    item[keys[k]] = v

            # track present fields, set defaults
            for k in flds:
                v = None
                if k in item:
                    present.add(k)
                else:
                    item[k] = tmplt[k]

            items.append(item)

        def emit(x):
            self.request.write(x)

        def wemit(x):
            """emit something using wiki parser"""
            wk = text_moin_wiki.Parser(x, self.request)
            wk.format(formatter)

        f = formatter

        emit(f.table(1))

        # show headings
        emit(f.table_row(1))
        for k in [fld for fld in flds if fld in present]:
            emit(f.table_cell(1))
            wemit("'''"+str(headings[k])+"'''")
            emit(f.table_cell(0))
        emit(f.table_row(0))

        for item in items:
            try:
                done = '2611' if int(item['percent']) == 100 else '2610'
            except:  # int() raised something
                done = '2610'

            emit(f.table_row(1))

            for k in [fld for fld in flds if fld in present]:

                emit(f.table_cell(1))
                txt = unicode(item[k])
                if k == 'title': txt = u'&#x%s; %s' % (done, txt)
                wemit(txt)
                emit(f.table_cell(0))

            emit(f.table_row(0))

            if 'log' in item:
                emit(f.table_row(1))
                emit(f.table_cell(1))  # empty cell
                emit(f.table_cell(0))
                emit(f.table_cell(1, colspan = len(present)-1))
                wemit(unicode(item['log']))
                emit(f.table_cell(0))
                emit(f.table_row(0))

        emit(f.table(0))
