# w.c.s. - web application for online forms
# Copyright (C) 2005-2013  Entr'ouvert
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, see <http://www.gnu.org/licenses/>.

import cgi

from qommon import _
from qommon.form import *
from qommon.template import TemplateError
from qommon import get_logger

from wcs.workflows import WorkflowStatusItem, register_item_class, template_on_formdata


class JournalEvolutionPart: #pylint: disable=C1001
    content = None

    def __init__(self, formdata, message):
        if not message:
            return
        if message.startswith('<'): # treat it as html
            def escape(x):
                if isinstance(x, basestring):
                    return cgi.escape(x)
                return x
            escape_function = escape
        else:
            escape_function = None
        self.content = template_on_formdata(formdata, message, process=escape_function)

    def view(self):
        if not self.content:
            return ''
        if self.content.startswith('<'):
            return htmltext(self.content)
        else:
            # use empty lines to mark paragraphs
            return htmltext('<p>') + \
                   htmltext('\n').join(
                            [(x or htmltext('</p><p>')) for x in self.content.splitlines()]) + \
                   htmltext('</p>')

    def get_json_export_dict(self, anonymise=False):
        d = {
            'type': 'workflow-comment',
        }
        if not anonymise:
            d['content'] = self.content
        return d


class RegisterCommenterWorkflowStatusItem(WorkflowStatusItem):
    description = N_('Record in Log')
    key = 'register-comment'

    comment = None

    def add_parameters_widgets(self, form, parameters, prefix='', formdef=None):
        if 'comment' in parameters:
            form.add(TextWidget, '%scomment' % prefix, title=_('Comment'),
                value=self.comment, cols=80, rows=10)

    def get_parameters(self):
        return ('comment',)

    def perform(self, formdata):
        if not formdata.evolution:
            return
        try:
            formdata.evolution[-1].add_part(JournalEvolutionPart(formdata, self.comment))
            formdata.store()
        except TemplateError as e:
            url = formdata.get_url()
            get_logger().error('error in template for comment [%s], '
                               'comment could not be generated: %s' % (url, str(e)))


register_item_class(RegisterCommenterWorkflowStatusItem)
