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

from quixote import get_request, get_response
from quixote.directory import Directory

from ..qommon import errors

from wcs.api import get_user_from_api_query_string, is_url_signed
from wcs.roles import logged_users_role
from wcs.workflows import (
        WorkflowGlobalActionWebserviceTrigger,
        get_role_translation,
        perform_items)


class HookDirectory(Directory):
    _q_exports = ['']

    def __init__(self, formdata, action, trigger):
        self.formdata = formdata
        self.action = action
        self.trigger = trigger

    def _q_index(self):
        get_response().set_content_type('application/json')

        if not get_request().get_method() == 'POST':
            raise errors.AccessForbiddenError('must be POST')

        user = get_user_from_api_query_string() or get_request().user
        if self.trigger.roles:
            for role in self.trigger.roles:
                if role == logged_users_role().id and (user or is_url_signed()):
                    break
                if role == '_submitter' and self.formdata.is_submitter(user):
                    break
                if not user:
                    continue
                if get_role_translation(self.formdata, role) in user.get_roles():
                    break
            else:
                raise errors.AccessForbiddenError('insufficient roles')

        if hasattr(get_request(), '_json'):
            workflow_data = {self.trigger.identifier: get_request().json}
            self.formdata.update_workflow_data(workflow_data)
            self.formdata.store()
        perform_items(self.action.items, self.formdata)
        return json.dumps({'err': 0})


class WorkflowGlobalActionWebserviceHooksDirectory(Directory):
    def __init__(self, formdata):
        self.formdata = formdata

    def _q_lookup(self, component):
        for action in self.formdata.formdef.workflow.global_actions:
            for trigger in action.triggers or []:
                if isinstance(trigger, WorkflowGlobalActionWebserviceTrigger):
                    if trigger.identifier == component:
                        return HookDirectory(self.formdata, action, trigger)
        raise errors.TraversalError()
