<%@page contentType="text/html;charset=UTF-8" pageEncoding="ISO-8859-1" session="true"%>
<%@page errorPage="AdminException.jsp"
%><%@page import="com.fujitsu.iflow.model.workflow.WFSession"
%><%@page import="com.fujitsu.iflow.model.workflow.WFAdminSession"
%><%@page import="com.fujitsu.iflow.model.wfcore.WFAdminSessionImpl"
%><%@page import="com.fujitsu.iflow.model.workflow.ProcessInstance"
%><%@page import="com.fujitsu.iflow.model.workflow.WFObjectList"
%><%@page import="com.fujitsu.iflow.model.workflow.WFObjectFactory"
%><%@page import="com.fujitsu.iflow.server.dataobjects.ProcessInstanceStatesEnum"
%><%@page import="com.fujitsu.iflow.server.dataobjects.FilterEnum"
%><%@page import="com.fujitsu.iflow.model.workflow.Filter"
%><%@page import="com.fujitsu.iflow.model.util.QuickForm"
%><%@page import="java.util.Date"
%><%@page import="java.util.Enumeration"
%><%@page import="com.fujitsu.iflow.model.util.URLEncoder"
%><%@page import="com.fujitsu.iflow.model.bpm.BPMAdmin"
%><%@page import="com.fujitsu.iflow.model.bpm.BPMSession"
%><%@page import="com.fujitsu.iflow.model.bpmcore.BPMAdminImpl"
%><%
    request.setCharacterEncoding("UTF-8");request.getParameterNames(); //Need dummy call for WL9.1
    BPMSession bps = (BPMSession) session.getAttribute("BPMSession");
    if (bps == null) {
        %><jsp:include page="PasswordPanel.jsp" flush="true"/><%
        return;
    }

    BPMAdmin bpas = bps.getAdmin();
    WFAdminSessionImpl wfSession = ((BPMAdminImpl)bpas)._wfas;

    String[] bcolor = {"evenrow","oddrow"};
    int nextColor = 0;
    String rowColor = bcolor[nextColor];
    session.setAttribute("TabIndex","1");

    String piSortedURL= "SortedListProcessInstances.jsp";

    int _pageSize = 20;
    int selIdValue=1;
    long id = -1;
    long processId = -1;

    String pageOption = request.getParameter("wPageId");
    if (!(pageOption != null && pageOption.length() >= 1))
    {
    pageOption = "1";
    }

    //DO NOT MERGE THE ABOVE CODE INTO THE IF-LOOP below
    int wPageValue = Integer.parseInt(pageOption);
    if (wPageValue < 1)
    wPageValue = 1;

    String planId = request.getParameter("planId");

    if (planId == null) {
    planId = (String) session.getAttribute("planId");
    }

    id = Long.parseLong(planId);
    session.setAttribute("planId",planId);

    ProcessInstance[] procInsts = getProcesses(FilterEnum._AllProcesses, wPageValue, _pageSize, wfSession, planId);
    // stupid habit of returning null for empty set
    if (procInsts == null) {
    procInsts = new ProcessInstance[0];
    }

%>
<html>
<head>
<title>Interstage Business Process Manager | Process Instance List</title>
<jsp:include page="StyleSheet.jsp" flush="true"/>
<script language="javascript" src="styles/clockscripts.js"></script>
<script>
function setSelection(wiForm, selPage)
{
    wiForm.wPageId.value = selPage
    location.href='ListProcessInstances.jsp?planId='+ wiForm.planId.value +'&wPageId=' + selPage
}

function setProcessId(val, id, adProcessForm)
{
    adProcessForm.processId.value= id
    adProcessForm.selected.value= val
    adProcessForm.submit()
}

function gotoProcessId()
{
    if (document.adProcessForm.processInstanceId.value == "" || isNaN(document.adProcessForm.processInstanceId.value))
    {
	        alert("Please enter a valid Process Instance ID.");
	        document.adProcessForm.processInstanceId.focus();
	        document.adProcessForm.processInstanceId.select();
	        return false;
    }
    location.href="ProcessSummary.jsp?processId=" + document.adProcessForm.processInstanceId.value;
}

function archiveQuery()
{
    document.location.href='ArchiveProcesses.jsp';
}

function archivedProcesses()
{
    location.href="ArchivedProcesses.jsp";
}

function filter()
{
    location.href="FilterProcesses.jsp";
}

 function getSelected(opt)
 {
    var selected = new Array();
    var index = 0;
    if(document.adProcessForm.pnum.value == 1)
    {
       if(opt.checked)
       {
          index = selected.length;
          selected[index] = new Object;
          selected[index].value = opt.value;
          selected[index].index = 0;
       }
    }
    else
    {
       for(var intLoop = 0; intLoop < opt.length; intLoop++)
       {
          if((opt[intLoop].selected) || (opt[intLoop].checked))
          {
              index = selected.length;
              selected[index] = new Object;
              selected[index].value = opt[intLoop].value;
              selected[index].index = intLoop;
          }
       }
    }
    return selected;
 }

 function outputSelected(val, opt, planId) {
    var sel = getSelected(opt);
    var strSel = "";
    for (var item in sel)
       strSel += sel[item].value + ",";
    var test = strSel.substring(0,strSel.length-1);
    var selected;
    if (val == 7) {
            selected = 'delete';
        }
        else
        {
            selected = 'archive';
    }
    if(test == "")
    {
        alert("Select Process Instance id's to " + selected + " multiple Process Instances.");
    }
    else
    {
    	adProcessForm.processId.value= test;
    	adProcessForm.selected.value= val; 
    	adProcessForm.planId.value= planId; 
    	adProcessForm.submit()
    }
 }

function migrateProcesses(opt) {
    var sel = getSelected(opt);
    var strSel = "";
    for (var item in sel)
       strSel += sel[item].value + ",";
    var test = strSel.substring(0,strSel.length-1);
    if(test == "")
    {
        alert("Select process instance id's for migrating multiple process instances.");
    }
    else
    {
    document.location.href = 'MigrateProcesses.jsp?processIds=' + test;
    }
 }
 
function disableEnterKey()
{
var code = window.event.keyCode;
    if (code == 13)
    {
        window.event.keyCode = 0;
    }
}

</script>
</head>

<body class="adminBodyClass">
<center>

<jsp:include page="AdminHeader.jsp" flush="true"/>
<form name="adProcessForm" method="get" action="ProcessSummary.jsp" onKeyPress="disableEnterKey()">
  <input type="hidden" name="wPageId" value="<%= wPageValue %>">
  <input type="hidden" name="selId" value="<%= selIdValue %>">
  <input type="hidden" name="planId" value="<%= planId %>">
  <input type="hidden" name="processId" value="-1">
  <input type="hidden" name="selected" value="Summary">

<table width="95%" border="0" cellpadding="2" cellspacing="2" align="center" class="tableclass">
<tr>
    <td align ="left" width="10%"><input type="button" onClick="archiveQuery()" value="Archive by Date" name="check" class="core-button">
    <input value="Filter" enabled type="button" onClick="filter()" class="submitClass"></td>
    <td width="10%">&nbsp;</td>
    <td width ="60%">&nbsp;</td>
<%
    String selOption = "setSelection(this.form, " + (wPageValue + 1) +")";
    String btnEnabled = "";
    
        if (wPageValue > 1 && _pageSize != 0)
            selOption = "setSelection(this.form, " + (wPageValue -1) +")";
        else {
            //selOption = "setSelection(this.form, 1)";
            btnEnabled = "disabled";
        }
%>
    <td width="10%"><input value="Prev Page" <%= btnEnabled %> type="button" onClick="<%= selOption %>" class="submitClass"></td>
<%
            
    btnEnabled = "";
    selOption = "setSelection(this.form, " + (wPageValue + 1) +")";
    
    if (procInsts.length < _pageSize || _pageSize == 0)
            btnEnabled = "disabled";    
    else
    {
        ProcessInstance[] mprocInsts = getProcesses(FilterEnum._AllProcesses, wPageValue+1, _pageSize, wfSession, planId);
        if(mprocInsts == null || mprocInsts.length == 0)
           btnEnabled = "disabled";
    }     
    
%>
    
    <td width="10%"><input value="Next Page" <%= btnEnabled %> type="button" onClick="<%= selOption %>" class="submitClass"></td>

</tr>

<tr>
    <td width ="10%"><input type="button" onClick="archivedProcesses()" value="Archived Process Instances" name="check" class="core-button"></td>
    <td width="10%"></td>
    <td width ="60%">&nbsp;</td>
    <td width="10%">Process Instance Id:</td><td width="8" align=right"><input type= "textbox" name ="processInstanceId" value = "" size = 10></td>
    <td width ="10" align ="right"><input type = "button" onClick=gotoProcessId() value = "Goto" class="submitClass">
    </td>
</tr>
</table>

<table bgcolor="#CCCCCC" border="0" cellpadding="4" cellspacing="1" class="tableClass" width="95%" align="center">
<tr align="center" class="headrow">
    <td bgcolor="#EEEEEE" style="filter:progid:DXImageTransform.Microsoft.Gradient(startColorStr='#FFFFFF', endColorStr='#6699CC', gradientType='1')"><font color="#000000" size="2">All process instances for process definition id <%= planId%></font></td>
</tr>
</table>

<TABLE bgcolor="#CCCCCC" border="0" cellpadding="4" cellspacing="1" class="tableClass" width="95%" align="center">
<tr align="center" class="headrow">
    <th>Select</th>
    <td><a href="<%=piSortedURL%>?sort=processId"><font color="#FFFFFF"> Id </font></a></td>
    <th><a href="<%=piSortedURL%>?sort=processName"><font color="#FFFFFF">  Process Instance Name </font></a></th>
    <th><a href="<%=piSortedURL%>?sort=planName"><font color="#FFFFFF"> Process Definition Name </font></a></th>
    <th>Date Started </th>
    <th><a href="<%=piSortedURL%>?sort=processStatus"><font color="#FFFFFF"> State </font></a></th>
    <th> Owner(s) </th>
    <th>&nbsp;</th>
    <th>&nbsp;</th>
    <th>&nbsp;</th>
</tr>
                  <%
    for (int i = 0; i < procInsts.length; i++)
    {
        ProcessInstance pi = procInsts[i];
        long piId = pi.getId();
        String piName = pi.getName();
        String planName = pi.getPlanName();
        String piState = null;
        int processState = pi.getState();
        switch(processState)
        {
            case 0: piState =  "Open";
                    break;
            case 1: piState = "NotRunning";
                    break;
            case 2: piState = "NotStarted";
                    break;
            case 3: piState = "Created";
                    break;
            case 4: piState = "Initialized";
                    break;
            case 5: piState = "Dormant";
                    break;
            case 6: piState = "Locked";
                    break;
            case 7: piState = "Running";
                    break;
            case 8: piState =  "Closed";
                    break;
            case 9: piState =  "Completed";
                    break;
            case 10: piState =  "Error";
                    break;
            case 11: piState =  "Aborted";
                    break;
            case 12: piState =  "Suspended";
                    break;
        }
        String[] piOwners = pi.getOwners();
        String piURL = "ProcessInstance.jsp?piId="+pi.getId();
        String pdURL = "ProcessDefinition.jsp?planId="+pi.getPlanId();
        String summaryURL = "ProcessSummary.jsp?processId="+piId;
        String piDate = ""+pi.getCreationTime();
        rowColor = bcolor[nextColor];
        nextColor = (nextColor + 1)%2;
        String summary ="Summary";
        String Copy = "Copy";
%>
<tr class="<%=rowColor%>">
    <td><INPUT TYPE=CHECKBOX NAME= selIds VALUE="<%= piId %>"></td>
    <td><%= piId %></td>
    <td><a href="<%=piURL%>"> <%= piName %> </a></td>
    <td><a href="<%=pdURL%>"> <%= planName %> </a></td>
    <td nowrap><script> showDate('<%=piDate%>'); </script></td>
    <td><%= piState %></td>
    <td>
                      <% for(int j=0; j<piOwners.length; j++){%>
                      <%= piOwners[j] %>
                      <% if(j!=piOwners.length-1) out.print(","); %>

                      <%}%>
    </td>
    <td>  
      <table border="0" cellspacing="0" cellpadding="0">
      <tr>
      <td><img src="images/buttons/details_small_icon.gif"></td>
      <td nowrap><a href="<%=summaryURL%>" title="Go here to modify this process instance">
      <div align="center" class="smalllinks">SUMMARY</div></a></td>
      </tr>
      </table>
	</td>
    <td>
      <table border="0" cellspacing="0" cellpadding="0">
      <tr>
      <td><img src="images/buttons/but_history.gif"></td>
      <td background="images/buttons/com_button_bg.gif" nowrap><a href="ShowHistory.jsp?id=<%=piId%>">
      <div align="center" class="buttonlink">History</div></a></td>
      <td width="9"><div align="right"><img src="images/buttons/com_button_right.gif" width="9" height="24"></div></td>
      </tr>
      </table>
    </td>

    <td>
      <table border="0" cellspacing="0" cellpadding="0">
      <tr>
      <td><img src="images/buttons/but_graphical_view.gif"></td>
      <td background="images/buttons/com_button_bg.gif" nowrap><a href="PIGraphic.jsp?piId=<%= piId %>">
      <div align="center" class="buttonlink">Snapshot</div></a></td>
      <td width="9"><div align="right"><img src="images/buttons/com_button_right.gif" width="9" height="24"></div></td>
      </tr>
      </table>
    </td>
</tr>
                  <%
   }
%>
</TABLE>

<%
if (procInsts.length != 0)
{
%>
<input type="hidden" name=pnum value="<%= procInsts.length %>">
<br>
<TABLE border="0" cellpadding="4" cellspacing="1" class="tableClass" width="95%" align="center"
<tr>
    <td>
    <input type="button" onClick="outputSelected('7', this.form.selIds, this.form.planId.value)" value="Delete Selected" name="check" class="core-button">

    <input type="button" onClick="outputSelected('8', this.form.selIds, this.form.planId.value)" value="Archive Selected" name="check" class="core-button">
    
    <input type="button" onClick="migrateProcesses(this.form.selIds)" value="Migrate Selected" name="migrate" class="core-button">
    </td>
</tr>
</table>
<%
}
%>

</form>
</center>
</html>

<%!

    public
    ProcessInstance[]
    getProcesses(
        int filterOption,
        int batchNumber,
        int batchSize,
        WFSession wfSession, String planId)
        throws Exception
    {
        WFObjectList wfObjectList = null;
        ProcessInstance[] piList = null;

        try {
            wfObjectList = WFObjectFactory.getWFObjectList(wfSession);
            wfObjectList.addFilter(WFObjectList.LISTFIELD_PLAN_ID,WFObjectList.SQLOP_EQUALTO,"'" + planId + "'");
            Object[] objList = null;
            wfObjectList.openBatchedList(filterOption);
            objList = wfObjectList.getNextBatch(batchSize);
            if (batchNumber > 1) {
                for (int i=1; i<batchNumber; i++) {
                    objList = wfObjectList.getNextBatch(batchSize);
                }
            }

            if (objList != null && objList.length > 0) {
                piList = new ProcessInstance[objList.length];
                for (int i=0; i<objList.length; i++) {
                    piList[i] = (ProcessInstance)objList[i];
                }
            }
        }
        finally {
            if (wfObjectList != null)
                wfObjectList.closeList();
        }

        return piList;
    }

    public WFAdminSessionImpl getiFlowSession(Object modelObject)
    {
            return (WFAdminSessionImpl)(modelObject);
    }


%>
