/**
 * Copyright 2010 JBoss Inc
 *
 * 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.integration.console;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.security.Principal;
import java.security.acl.Group;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;

import javax.security.auth.Subject;
import javax.security.jacc.PolicyContext;

import org.jboss.bpm.console.client.model.TaskRef;
import org.jbpm.task.AccessType;
import org.jbpm.task.Status;
import org.jbpm.task.Task;
import org.jbpm.task.TaskService;
import org.jbpm.task.query.TaskSummary;
import org.jbpm.task.service.ContentData;
import org.jbpm.task.service.responsehandlers.BlockingTaskOperationResponseHandler;

public class TaskManagement extends SessionInitializer implements org.jboss.bpm.console.server.integration.TaskManagement {
	
	private static int clientCounter = 0;
    
	private TaskService service;
	
	public TaskManagement () {
	    super();
	}
	
	public void connect() {

	    if (service == null) {
	        
    	    Properties jbpmConsoleProperties = StatefulKnowledgeSessionUtil.getJbpmConsoleProperties();   
            service = TaskClientFactory.newInstance(jbpmConsoleProperties, "org.jbpm.integration.console.TaskManagement"+clientCounter);
            clientCounter++;
       
	    }
		
	}
	
	public TaskRef getTaskById(long taskId) {
		connect();
		Task task = service.getTask(taskId);
		
        return Transform.task(task);
	}

	public void assignTask(long taskId, String idRef, String userId) {
		connect(); 
		
		if (idRef == null) {
			service.release(taskId, userId);
		} else if (idRef.equals(userId)) {
			List<String> roles = getCallerRoles();
			if (roles == null) {
				service.claim(taskId, idRef);
			} else {
				service.claim(taskId, idRef, roles);
			}
		} else {

			service.delegate(taskId, userId, idRef);
		}
		
	}

	public void completeTask(long taskId, Map data, String userId) {
		connect();
		
		service.start(taskId, userId);
		
		ContentData contentData = null;
		if (data != null) {
			ByteArrayOutputStream bos = new ByteArrayOutputStream();
			ObjectOutputStream out;
			try {
				out = new ObjectOutputStream(bos);
				out.writeObject(data);
				out.close();
				contentData = new ContentData();
				contentData.setContent(bos.toByteArray());
				contentData.setAccessType(AccessType.Inline);
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
  
		service.complete(taskId, userId, contentData);
		
	}

	@SuppressWarnings("unchecked")
	public void completeTask(long taskId, String outcome, Map data, String userId) {
	    if ("jbpm_skip_task".equalsIgnoreCase(outcome)) {
	        skipTask(taskId, userId);
	    } else {
    		data.put("outcome", outcome);
    		completeTask(taskId, data, userId);
	    }
	}

	public void releaseTask(long taskId, String userId) {
		// TODO: this method is not being invoked, it's using
		// assignTask with null parameter instead
		connect(); 
		service.release(taskId, userId);
		 
	}

	public List<TaskRef> getAssignedTasks(String idRef) {
		connect();
        List<TaskRef> result = new ArrayList<TaskRef>();
		try {
			List<TaskSummary> tasks = service.getTasksOwned(idRef, "en-UK");
			
	        for (TaskSummary task: tasks) {
	        	if (task.getStatus() == Status.Reserved) {
	        		result.add(Transform.task(task));
	        	}
	        }
		} catch (Throwable t) {
			t.printStackTrace();
		}
		return result;
	}

	public List<TaskRef> getUnassignedTasks(String idRef, String participationType) {
		// TODO participationType ?
		connect();
        List<TaskRef> result = new ArrayList<TaskRef>();
		try {
            
			List<String> roles = getCallerRoles();
			List<TaskSummary> tasks = null;
			
			if (roles == null) {
				tasks = service.getTasksAssignedAsPotentialOwner(idRef, "en-UK");
			} else {
				tasks = service.getTasksAssignedAsPotentialOwner(idRef, roles, "en-UK");
			}
			
			
	        for (TaskSummary task: tasks) {
	        	result.add(Transform.task(task));
	        }
		} catch (Throwable t) {
			t.printStackTrace();
		}
		return result;
	}
	
	public void skipTask(long taskId, String userId) {
	    connect();
        service.skip(taskId, userId);
	}

    private List<String> getCallerRoles() {
        List<String> roles = null;
        try {
            Subject subject = (Subject) PolicyContext.getContext("javax.security.auth.Subject.container");
    
            if (subject != null) {
                Set<Principal> principals = subject.getPrincipals();
    
                if (principals != null) {
                    roles = new ArrayList<String>();
                    for (Principal principal : principals) {
                        if (principal instanceof Group  && "Roles".equalsIgnoreCase(principal.getName())) {
                            Enumeration<? extends Principal> groups = ((Group) principal).members();
                            
                            while (groups.hasMoreElements()) {
                                Principal groupPrincipal = (Principal) groups.nextElement();
                                roles.add(groupPrincipal.getName());
                               
                            }
                            break;
    
                        }
    
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return roles;
    }

}

@@ -817,24 +817,54 @@
 .ArrayList;%0A
+import java.util.Collections;%0A
 import java.
@@ -3810,16 +3810,94 @@
 %09%09try %7B%0A
+%09%09    List%3CStatus%3E onlyReserved = Collections.singletonList(Status.Reserved);%0A
 %09%09%09List%3C
@@ -3941,24 +3941,38 @@
 Owned(idRef,
+ onlyReserved,
  %22en-UK%22);%0A%09
@@ -4029,62 +4029,8 @@
    %09
-if (task.getStatus() == Status.Reserved) %7B%0A%09        %09%09
 resu
@@ -4063,20 +4063,8 @@
 ));%0A
-%09        %09%7D%0A
 %09   
@@ -4425,24 +4425,89 @@
  = null;%0A%09%09%09
+List%3CStatus%3E onlyReady = Collections.singletonList(Status.Ready);
 %0A%09%09%09if (role
@@ -4571,22 +4571,41 @@
 ialOwner
-(idRef
+ByStatus(idRef, onlyReady
 , %22en-UK
@@ -4672,16 +4672,31 @@
 ialOwner
+ByStatusByGroup
 (idRef, 
@@ -4701,16 +4701,27 @@
 , roles,
+ onlyReady,
  %22en-UK%22

make sure that tasks returned are in proper status