## $Id: workflow.py 12168 2014-12-08 06:17:30Z henrik $
##
## Copyright (C) 2014 Uli Fouquet & Henrik Bettermann
## 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, write to the Free Software
## Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
##
"""Workflow for documents.
"""
import grok
from datetime import datetime
from zope.component import getUtility
from hurry.workflow.workflow import Transition, WorkflowState, NullCondition
from hurry.workflow.interfaces import (
    IWorkflowState, IWorkflowTransitionEvent, InvalidTransitionError)
from waeup.ikoba.interfaces import (
    IObjectHistory, IIkobaWorkflowInfo,
    SimpleIkobaVocabulary,
    CREATED, SUBMITTED, VERIFIED, REJECTED, EXPIRED)
from waeup.ikoba.interfaces import MessageFactory as _
from waeup.ikoba.workflow import IkobaWorkflow, IkobaWorkflowInfo
from waeup.ikoba.utils.helpers import get_current_principal
from waeup.ikoba.documents.interfaces import IDocument

IMPORTABLE_STATES = (CREATED, SUBMITTED, VERIFIED, REJECTED, EXPIRED)

VERIFICATION_TRANSITIONS = (
    Transition(
        transition_id = 'create',
        title = _('Create document'),
        source = None,
        condition = NullCondition,
        msg = _('Document created'),
        destination = CREATED),

    Transition(
        transition_id = 'submit',
        title = _('Submit for verification'),
        msg = _('Submitted for verification'),
        source = CREATED,
        destination = SUBMITTED),

    Transition(
        transition_id = 'verify',
        title = _('Verify'),
        msg = _('Verified'),
        source = SUBMITTED,
        destination = VERIFIED),

    Transition(
        transition_id = 'reject',
        title = _('Reject'),
        msg = _('REJECTED'),
        source = SUBMITTED,
        destination = REJECTED),

    Transition(
        transition_id = 'reset1',
        title = _('Reset to initial state'),
        msg = _('Reset to initial state'),
        source = REJECTED,
        destination = CREATED),

    Transition(
        transition_id = 'reset2',
        title = _('Reset to initial state'),
        msg = _('Reset to initial state'),
        source = VERIFIED,
        destination = CREATED),

    Transition(
        transition_id = 'reset3',
        title = _('Reset to initial state'),
        msg = _('Reset to initial state'),
        source = SUBMITTED,
        destination = CREATED),

    Transition(
        transition_id = 'expire',
        title = _('Set to expired'),
        msg = _('Set to expired'),
        source = VERIFIED,
        destination = EXPIRED),

    Transition(
        transition_id = 'reset4',
        title = _('Reset to initial state'),
        msg = _('Reset to initial state'),
        source = EXPIRED,
        destination = CREATED),
    )


IMPORTABLE_TRANSITIONS = [i.transition_id for i in VERIFICATION_TRANSITIONS]

verification_workflow = IkobaWorkflow(VERIFICATION_TRANSITIONS)

class VerificationWorkflowState(WorkflowState, grok.Adapter):
    """An adapter to adapt Document objects to workflow states.
    """
    grok.context(IDocument)
    grok.provides(IWorkflowState)

    state_key = 'wf.verification.state'
    state_id = 'wf.verification.id'

class VerificationWorkflowInfo(IkobaWorkflowInfo, grok.Adapter):
    """Adapter to adapt Document objects to workflow info objects.
    """
    grok.context(IDocument)
    grok.provides(IIkobaWorkflowInfo)

    def __init__(self, context):
        self.context = context
        self.wf = verification_workflow

@grok.subscribe(IDocument, IWorkflowTransitionEvent)
def handle_document_transition_event(obj, event):
    """Append message to document history and log file and update
    last_transition_date when transition happened.

    Undo the verification of document and raise an exception if document
    does not meet the requirements for verification.
    """
    if event.transition.destination == VERIFIED:
        verifiable, error = obj.is_verifiable
        if not verifiable:
            # Undo transition and raise an exception.
            IWorkflowState(obj).setState(event.transition.source)
            raise InvalidTransitionError(error)
    if event.transition.transition_id == 'verify':
        obj.setMD5()
    msg = event.transition.user_data['msg']
    history = IObjectHistory(obj)
    history.addMessage(msg)
    obj.last_transition_date = datetime.utcnow()
    try:
        customers_container = grok.getSite()['customers']
        customers_container.logger.info('%s - %s' % (obj.customer_id,msg))
    except (TypeError, AttributeError):
        pass
    return
