package edu.yu.einstein.wasp.batch;


import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import edu.yu.einstein.wasp.model.State;
import edu.yu.einstein.wasp.model.Task;
import edu.yu.einstein.wasp.model.Workflow;
import edu.yu.einstein.wasp.service.StateService;
import edu.yu.einstein.wasp.service.TaskService;
import edu.yu.einstein.wasp.service.WorkflowService;

/**
 * Workflow Poller
 * polls job db for task/workflowid combos that are not final
 *
 */

@Service
public class WorkflowPoller {

	@Autowired
	StateService stateService;

	@Autowired
	TaskService taskService;

	@Autowired
	WorkflowService workflowService;
 
	protected String workflowIName; 
	public void setWorkflowIName(String s) {
		this.workflowIName = s;
	}

	protected String taskIName; 
	public void setTaskIName(String s) {
		this.taskIName = s;
	}

 
	@Transactional
	public List<State> getStates() {
		Workflow workflow = workflowService.getWorkflowByIName(workflowIName); 
		Task task = taskService.getTaskByIName(taskIName); 

		List<State> rt = new ArrayList();

		List<State> allStates = task.getState();

                if (allStates == null) { return rt; }

		for (State state: allStates) {
			if (state.getStatejob().isEmpty()) { continue; }
			if (state.getStatus().equals("FINAL")) { continue; }

			// should be the same so just get first, 
			// TODO check for npe
			if (state.getStatejob().get(0).getJob().getWorkflowId().intValue() != workflow.getWorkflowId().intValue()) {
				continue;
			}


			rt.add(state);
		}

		return rt; 
	}

}

@@ -1122,17 +1122,17 @@
 wIName);
- 
+%0A
 %0A%09%09Task 
@@ -1313,16 +1313,85 @@
 rn rt; %7D
+%0A                if (workflow.getWorkflowId() == null) %7B return rt; %7D
 %0A%0A%09%09for 
@@ -1596,16 +1596,25 @@
 for npe%0A
+%09%09%09try %7B%0A
 %09%09%09if (s
@@ -1736,16 +1736,62 @@
 e;%0A%09%09%09%7D%0A
+%09%09%09%7D catch (Exception e) %7B%0A%09%09%09%09continue;%0A%09%09%09%7D%0A
 %0A%0A%09%09%09rt.

check workflowid null