--
-- workflow_case__start_task/3
--
create or replace function workflow_case__start_task(
  integer,
  integer,
  integer
) returns int4 as $$

declare
  start_task__task_id                alias for $1;  
  start_task__user_id                alias for $2;  
  start_task__journal_id             alias for $3;  
  v_case_id                          integer;        
  v_workflow_key                     wf_workflows.workflow_key%TYPE;
  v_transition_key                   varchar(100);  
  v_hold_timeout_callback            varchar(100);  
  v_hold_timeout_custom_arg          varchar(4000); 
  v_hold_timeout                     timestamptz;     
  place_rec                          record;
begin
        PERFORM workflow_case__ensure_task_in_state(start_task__task_id, 
                                                    'enabled');
    
        select t.case_id, t.workflow_key, t.transition_key, ti.hold_timeout_callback, ti.hold_timeout_custom_arg 
        into   v_case_id, v_workflow_key, v_transition_key, v_hold_timeout_callback, v_hold_timeout_custom_arg
        from   wf_tasks t, wf_cases c, wf_transition_info ti
        where  t.task_id = start_task__task_id
        and    c.case_id = t.case_id
        and    ti.context_key = c.context_key
        and    ti.workflow_key = t.workflow_key
        and    ti.transition_key = t.transition_key;

        v_hold_timeout := workflow_case__execute_hold_timeout_callback (
                       v_hold_timeout_callback, 
                       v_hold_timeout_custom_arg, 
                       v_case_id, v_transition_key);

        /* Mark it started */

        update wf_tasks 
        set    state = 'started', 
               started_date = now(),
               holding_user = start_task__user_id, 
               hold_timeout = v_hold_timeout
        where task_id = start_task__task_id;
    
        
        /* Reserve one token from each input place */

        for place_rec in select *
        from   wf_transition_places tp
        where  tp.workflow_key = v_workflow_key
        and    tp.transition_key = v_transition_key
        and    direction = 'in'
        LOOP
            PERFORM workflow_case__lock_token (  
                v_case_id,
                place_rec.place_key,
                start_task__journal_id,
                start_task__task_id
            );
        end loop;

        return 0; 
end;$$ language plpgsql;