from __future__ import absolute_import

import swf.models
import swf.querysets
from simpleflow.history import History


# TODO: move this function inside a QuerySet object when we merge the
# "simpleflow" and "swf" namespaces
def get_workflow_history(domain_name, workflow_id, run_id=None):
    domain = swf.models.Domain(domain_name)

    # if no run_id provided, we assume that the requester wanted the last
    # execution with that workflow_id
    if not run_id:
        found_run_id = None
        qs = swf.querysets.WorkflowExecutionQuerySet(domain)
        wfe = qs.filter(workflow_id=workflow_id, status=swf.models.WorkflowExecution.STATUS_OPEN) or \
                qs.filter(workflow_id=workflow_id, status=swf.models.WorkflowExecution.STATUS_CLOSED)
        if wfe:
            # by default, workflow executions are returned in descending start time order
            # so the first returned is the last that has run
            found_run_id = wfe[0].run_id

    workflow_execution = (
        swf.querysets.WorkflowExecutionQuerySet(domain).get(
            workflow_id=workflow_id,
            run_id=run_id or found_run_id,
        )
    )

    return History(workflow_execution.history())

@@ -33,16 +33,38 @@
 import%0A%0A
+import swf.exceptions%0A
 import s
@@ -258,23 +258,25 @@
 orkflow_
-history
+execution
 (domain_
@@ -990,43 +990,212 @@
 _id%0A
-%0A    workflow_execution = (%0A       
+        else:%0A            # we would send a malformed request to SWF API, better stop directly%0A            raise ValueError(%22Couldn't find an execution with workflowId=%7B%7D%22.format(workflow_id))%0A%0A    return
  swf
@@ -1244,20 +1244,16 @@
 n).get(%0A
-    
         
@@ -1285,20 +1285,16 @@
         
-    
 run_id=r
@@ -1324,20 +1324,270 @@
     
-    )%0A    )%0A
+)%0A%0A# TODO: move this function inside a QuerySet object when we merge the%0A# %22simpleflow%22 and %22swf%22 namespaces%0Adef get_workflow_history(domain_name, workflow_id, run_id=None):%0A    workflow_execution = get_workflow_execution(domain_name, workflow_id, run_id=run_id)
 %0A   

Split concerns in simpleflow.swf.utils and raise early if no execution found