# w.c.s. - web application for online forms
# Copyright (C) 2005-2018  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/>.

from quixote import redirect
from quixote.directory import Directory

from ..qommon import errors
from ..qommon import misc
from ..qommon import template
from ..qommon import tokens
from ..qommon.form import Form

from wcs.formdef import FormDef
from wcs.forms.common import FormTemplateMixin
from wcs.wf.jump import jump_and_perform


class MissingOrExpiredToken(errors.PublishError):
    status_code = 404
    title = N_('Error')
    description = N_('This action link has already been used or has expired.')


class ActionsDirectory(Directory):
    def _q_lookup(self, component):
        try:
            token = tokens.Token.get(component)
        except KeyError:
            raise MissingOrExpiredToken()
        if token.type != 'action':
            raise errors.TraversalError()
        return ActionDirectory(token)


class ActionDirectory(Directory, FormTemplateMixin):
    _q_exports = ['']
    templates = ['wcs/action.html']

    def __init__(self, token):
        self.token = token
        self.formdef = FormDef.get_by_urlname(self.token.context['form_slug'])
        self.formdata = self.formdef.data_class().get(self.token.context['form_number_raw'])
        self.action = None
        status = self.formdata.get_status()
        for item in status.items:
            if getattr(item, 'identifier', None) == self.token.context['action_id']:
                self.action = item
                break
        else:
            raise MissingOrExpiredToken()

    def _q_index(self):
        template.html_top(title=self.formdef.name)
        form = Form()
        form.add_submit('submit', misc.site_encode(self.token.context['label']))
        if form.is_submitted() and not form.has_errors():
            return self.submit()
        context = {
            'view': self,
            'form': form,
        }
        return template.QommonTemplateResponse(
                templates=list(self.get_formdef_template_variants(self.templates)),
                context=context)

    def submit(self):
        url = jump_and_perform(self.formdata, self.action)
        self.token.remove_self()
        if url:
            return redirect(url)
        context = {
            'view': self,
            'done': True,
        }
        return template.QommonTemplateResponse(
                templates=list(self.get_formdef_template_variants(self.templates)),
                context=context)
