/*
 * Copyright 2013 JBoss by Red Hat.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.jbpm.test.persistence;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.jbpm.process.instance.impl.demo.SystemOutWorkItemHandler;
import org.jbpm.services.task.admin.listener.TaskCleanUpProcessEventListener;
import org.jbpm.test.JbpmJUnitBaseTestCase;
import org.junit.Test;
import org.kie.api.runtime.KieSession;
import org.kie.api.runtime.manager.RuntimeEngine;
import org.kie.api.runtime.process.ProcessInstance;
import org.kie.api.task.TaskService;
import org.kie.api.task.model.TaskSummary;


public class CallActivitiesWithUserTasksProcessTest extends JbpmJUnitBaseTestCase{
    
    public CallActivitiesWithUserTasksProcessTest() {
        super(true, true);
    }
  
    @Test
    public void testCallActivitiesWithUserTasks() {
        createRuntimeManager("MainProcess.bpmn", "SubProcess.bpmn");
        RuntimeEngine runtimeEngine = getRuntimeEngine();
        KieSession ksession = runtimeEngine.getKieSession();
        TaskService taskService = runtimeEngine.getTaskService();
        
        ksession.addEventListener(new TaskCleanUpProcessEventListener(taskService));        
        ksession.getWorkItemManager().registerWorkItemHandler("Sysout", new SystemOutWorkItemHandler());
                 
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("pActorId", "john");
        ProcessInstance processInstance = ksession.startProcess("PolicyValueAnalysis", params);
        
        List<TaskSummary> tasks = taskService.getTasksAssignedAsPotentialOwner("john", "en-UK");
        assertNotNull(tasks);
        assertEquals(1, tasks.size());
        
        Long taskId = tasks.get(0).getId();

        taskService.start(taskId, "john");
        taskService.complete(taskId, "john", null);
        
        tasks = taskService.getTasksAssignedAsPotentialOwner("john", "en-UK");
        assertNotNull(tasks);
        assertEquals(1, tasks.size());
        
        taskId = tasks.get(0).getId();

        taskService.start(taskId, "john");
        taskService.complete(taskId, "john", null);
        
        assertProcessInstanceCompleted(processInstance.getId(), ksession);
        
    }
}
