# 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 _, ezt
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,
                           AttachmentEvolutionPart)

import sys

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

    def __init__(self, formdata, message):
        if not message:
            return
        if '{{' in message or '{%' in message:
            # django template
            content = template_on_formdata(formdata, message)
            if content and not content.startswith('<'):
                # add <div> to mark the string as processed as HTML
                content = '<div>%s</div>' % content
            self.content = content
            return

        if message.startswith('<'):
            # treat it as html, escape strings from ezt variables
            self.content = template_on_formdata(formdata, message,
                    ezt_format=ezt.FORMAT_HTML)
            return

        # treat is as text/plain
        self.content = template_on_formdata(formdata, message)

    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_('History Message')
    key = 'register-comment'
    category = 'interaction'

    comment = None
    attachments = None

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

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

    def attach_uploads_to_formdata(self, formdata, uploads):
        if not formdata.evolution[-1].parts:
            formdata.evolution[-1].parts = []
        for upload in uploads:
            try:
                # useless but required to restore upload.fp from serialized state,
                # needed by AttachmentEvolutionPart.from_upload()
                fp = upload.get_file_pointer()
                formdata.evolution[-1].add_part(AttachmentEvolutionPart.from_upload(upload))
            except:
                get_publisher().notify_of_exception(sys.exc_info(),
                                                    context='[comment/attachments]')
            continue

    def perform(self, formdata):
        if not formdata.evolution:
            return

        # process attachments first, they might be used in the comment
        # (with substitution vars)
        if self.attachments:
            uploads = self.convert_attachments_to_uploads()
            self.attach_uploads_to_formdata(formdata, uploads)
            formdata.store()  # store and invalidate cache, so references can be used in the comment message.

        # the comment can use attachments done above
        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)
