--
-- workflow_case__get_task_deadline/5
--
create or replace function workflow_case__get_task_deadline(
  character varying,
  character varying,
  character varying,
  integer,
  character varying
) returns timestamptz as $$

declare
  get_task_deadline__callback               alias for $1;  
  get_task_deadline__custom_arg             alias for $2;  
  get_task_deadline__attribute_name         alias for $3;  
  get_task_deadline__case_id                alias for $4;  
  get_task_deadline__transition_key         alias for $5;  
  v_deadline                                timestamptz;
  v_rec                                     record;
  v_str                                     varchar;
begin
        /*
         * 1. or if there is a row in wf_case_deadlines, we use that
         * 2. if there is a callback, we execute that
         * 3. otherwise, if there is an attribute, we use that
         */

        /* wf_case_deadlines */
        select deadline into v_deadline
            from wf_case_deadlines
            where case_id = get_task_deadline__case_id
            and   transition_key = get_task_deadline__transition_key;

        if NOT FOUND then
            if get_task_deadline__callback != '' and get_task_deadline__callback is not null then
                /* callback */
                v_str := 'select ' || get_task_deadline__callback || '(' || 
                         get_task_deadline__case_id || ',' || 
                         quote_literal(get_task_deadline__transition_key) || ',' || 
                         coalesce(quote_literal(get_task_deadline__custom_arg),'null') || ') as deadline';

                for v_rec in execute v_str
                LOOP
                    v_deadline := v_rec.deadline;
                    exit;
                end LOOP;
            else if get_task_deadline__attribute_name != '' and get_task_deadline__attribute_name is not null then
                /* attribute */
                v_deadline := acs_object__get_attribute (
                    get_task_deadline__case_id,
                    get_task_deadline__attribute_name
                );
            else 
                v_deadline := null;
            end if; end if;
        end if;
        
        return v_deadline;
     
end;$$ language plpgsql;