<%@page contentType="text/html;charset=UTF-8" pageEncoding="ISO-8859-1" session="true"%>
<%@page errorPage="Exception.jsp"
%><%@page import="com.fujitsu.iflow.model.bpm.BPMSession"
%><%@page import="com.fujitsu.iflow.model.bpmcore.BPMSessionImpl"
%><%@page import="com.fujitsu.iflow.model.util.QuickForm"
%><%@page import="com.fujitsu.iflow.model.util.URLEncoder"
%><%@page import="com.fujitsu.iflow.model.workflow.WFSession"
%><%@page import="java.io.Writer"
%><%@page import="java.util.List"
%><%@page import="java.util.Map"
%><%@page import="java.util.ArrayList"
%><%@page import="java.util.Iterator"
%><%@page import="java.util.Enumeration"
%><%@page import="java.text.DateFormat"
%><%@page import="com.fujitsu.ibpm.dtm.*"
%>
<%-- calls the debug() function --%>
<%@ include file="Debug.jsp" %>

<%  //checks the session is valid or not 
    request.setCharacterEncoding("UTF-8");
    BPMSession bps = (BPMSession) session.getAttribute("BPMSession");
    if (bps == null) {
        %><jsp:include page="PasswordPanel.jsp" flush="true"/><%
        return;
    }
%>
<%@ include file="dtmCommon.jsp" %>
<%-- calls the getSortedTemplates() function --%>
<%@ include file="sortProcessDefinition.jsp" %>
<html>
<head>
<title>Interstage Business Process Manager | Approval DecisionTable Detail</title>
<link href="styles/dtm.css" rel="stylesheet" type="text/css">
<script type="text/javascript" language="javascript">

//trims all leading and trailing blank spaces
function Trim(decisionElementValue){
	if(decisionElementValue.length < 1){
		return"";
	}
	decisionElementValue = RTrim(decisionElementValue);
	decisionElementValue = LTrim(decisionElementValue);
	if(decisionElementValue==""){
		return "";
	}
	else{
		return decisionElementValue;
	}
} 
//trims all trailing blank spaces
function RTrim(decisionElementValue){
	var w_space = String.fromCharCode(32);
	var v_length = decisionElementValue.length;
	var tempdecisionElementValue = "";
	if(v_length < 0){
		return"";
	}
	var decisionTableIndex = v_length -1;

	while(decisionTableIndex > -1){
		if(decisionElementValue.charAt(decisionTableIndex) == w_space){
		}
		else{
			tempdecisionElementValue = decisionElementValue.substring(0,decisionTableIndex +1);
			break;
		}
		decisionTableIndex = decisionTableIndex-1;

	} 
return tempdecisionElementValue;

}
//trims all leading blank spaces
function LTrim(decisionElementValue){
	var w_space = String.fromCharCode(32);
	if(v_length < 1){
		return"";
	}
	var v_length = decisionElementValue.length;
	var tempdecisionElementValue = "";

	var decisionTableIndex = 0;

	while(decisionTableIndex < v_length){
		if(decisionElementValue.charAt(decisionTableIndex) == w_space){
		}
		else{
			tempdecisionElementValue = decisionElementValue.substring(decisionTableIndex,v_length);
			break;
		}
		decisionTableIndex = decisionTableIndex + 1;
	} 
return tempdecisionElementValue;
} 


function doSubmit()
{
var ScenarioElement=-1;
var isElementEmpty=true;
	//checks for all Decision elements are empty or not
	for(scenarioformIndex=0;scenarioformIndex<scenarioform.length;scenarioformIndex++)
	{	
		var decisionElement=document.scenarioform[++ScenarioElement].value;
		decisionElement=Trim(decisionElement);
		
		if(decisionElement==""){
				isElementEmpty=false;
		}
		else{
			isElementEmpty=true;
			break;
		}
	}
	//displays error message if all decision elements are empty
	if(isElementEmpty==false){
		alert("All Decision elements cannot be blank.");
		return;
	}
	
	document.scenarioform.submit();
}
</script>
<script type="text/javascript" language="javascript" src="jscript/check.js"> </script>
<style type="text/css">
<!--
.style1 {font-size: 100%}
-->
</style>
</head>
<body class="bodyClass">
<center>
  <jsp:include page="DTMHeader.jsp" flush="true"/><br/>
  
  	<%-- calls all the global variables --%>
	<%@ include file="commonDtmIterators.jsp" %>

<%
   
    String scenarioIdStr = request.getParameter("scenarioId");
	int scenarioId = -1;
	Scenario scenario = null;
 	
  if (actionStr != null && actionStr.length() > 0) {
        if (actionStr.equals("new")) {
         	scenario = decisionTable.getNewScenario();//creates a new Scenario
			scenarioId=scenario.getId();
        } if (actionStr.equals("delete")) {
			 scenarioId = (new Integer(scenarioIdStr)).intValue();
        	 dtm.deleteScenario(decisionTableId,scenarioId);
        } if (actionStr.equals("save")) {
			  scenario = (Scenario) session.getAttribute("Scenario");
		//set conditions to scenario
			  List conditions = new ArrayList();
			  int index=1;
			  while(conditionKeysItr.hasNext()){
				  ConditionKey conditionKey = (ConditionKey) conditionKeysItr.next();
				  String conditionValue = request.getParameter("ConditionValue"+conditionKey.getId()).toString();
				  conditions.add(new Condition(index++,"Condition"+index,conditionKey.getId(),conditionValue));

			  }
			  scenario.setConditions(dtm.formatConditions(decisionTable,conditions));

		//set selections to scenario
				 List selections = new ArrayList();
				 index=1;
				 while(possibleSelectionsItr.hasNext()){
					  String selection = possibleSelectionsItr.next().toString();
					  String selectedStr = request.getParameter("approval"+index);
					  selections.add(new Selection(index++,selection,selectedStr));
				}
			    scenario.setSelections(selections);
	     	 	dtm.saveScenario(decisionTableId,scenario);
        }
  }
  if(scenarioId==-1) scenarioId = (new Integer(scenarioIdStr)).intValue();
  String editUrl = "ScenarioDetail.jsp";


		if(scenario==null) scenario = dtm.getScenario(decisionTableId,scenarioId);
	    debug(trace, out, "\n scenario="+scenario.toString());
		session.setAttribute("Scenario",scenario);

%>

  <form name="scenarioform" method="post" action="DecisionTableDetail.jsp?pageaction=saveDecision&decisionTableId=<%=decisionTableId%>&scenarioId=<%=scenarioId%>">
  <TABLE  border="0" cellpadding="4" cellspacing="1" class="tableClass" width="100%" align="center">
    <tr>
      <td align="right" height="32" valign="top">&nbsp;</td>
    </tr>
  </table>
  <table border="0" cellpadding="4" cellspacing="1" class="tableClass" width="100%" align="center">
  <tr align="center" class="oddrow">
    <td align="right"><table border="0" cellpadding=0 cellspacing=0>
      <tr>
        <td align="right"><table border="0" cellspacing="0" cellpadding="0">
            <tr background="images/buttons/com_button_bg.gif">
              <td width="15"><img src="images/buttons/but_save.gif"></td>
              <td background="images/buttons/com_button_bg.gif" nowrap><a href="javascript:doSubmit();">
                <div align="center" class="buttonlink"> OK</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>&nbsp;</td>
        <td><table border="0" cellspacing="0" cellpadding="0">
            <tr background="images/buttons/com_button_bg.gif">
              <td width="15"><img src="images/buttons/cancel.gif"></td>
              <td background="images/buttons/com_button_bg.gif" nowrap><a href="DecisionTableDetail.jsp?decisionTableId=<%=decisionTableId%>">
                <div align="center" class="buttonlink"> Cancel</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></td>
  </tr>
  <tr align="center" class="headrow">
    <td align="right" bgcolor="#EEEEEE" class="style1" style="filter:progid:DXImageTransform.Microsoft.Gradient(startColorStr='#FFFFFF', endColorStr='#6699CC', gradientType='1')"><div align="left"><font color="#000000"> Decision: <%=scenario.getId()%> </font>
            <div align="right"> </div>
    </div></td>
  </tr>
  <tr align="center" class="oddrow">
    <td align="right" ><table bgcolor="#CCCCCC" border="0" cellpadding="4" cellspacing="1" class="tableClass" width="100%" align="center">
      <tr align="center" class="headrow" bgcolor="#0066CC" valign="top">
        <th align="center" class="style1"> Id</th>
        <%
			// sets Scenario table
						 StringBuffer tempStringForRowHeader = new StringBuffer();
						 tempStringForRowHeader.append("<tr align=\"center\" class=\"headrow\" bgcolor=\"#0066CC\" valign=\"top\"><th align=\"center\"> </th>");
						
						
						List tempPrimaryValues= new ArrayList();
						Iterator tempConditionKeysItr=conditionKeys.iterator();
						while(tempConditionKeysItr.hasNext()){
						ConditionKey conditionKey = (ConditionKey) tempConditionKeysItr.next();
						
						int compositeKeyId = -1;
						if(conditionKey.getType().equals(ConditionKey.COMPOSITE_VALUE)) {
							compositeKeyId = conditionKey.getId();
							
						
						if(compositeKeyId!=-1){
								 tempPrimaryValues = conditionKey.getPrimaryKeyValues();
						}
					}	
				}
						
						boolean isPrimaryValues=false;
						boolean isComposite=false;
						while(conditionKeysItr.hasNext()){
						ConditionKey conditionKey = (ConditionKey) conditionKeysItr.next();
						String selection = "";
						int compositeKeyId = -1;
						if(conditionKey.getType().equals(ConditionKey.COMPOSITE_VALUE)) {
							compositeKeyId = conditionKey.getId();
							isComposite=true;
						}
						String colspan="1";
						if(compositeKeyId!=-1){
								 List primaryValues = conditionKey.getPrimaryKeyValues();
								 if(primaryValues.size()>0) {
								 	colspan = ""+primaryValues.size();
								}else{
									tempStringForRowHeader.append("<th >  </th>");
								}
						}
						
						if(!conditionKey.isPassive())isPrimaryValues=true;
				//displays primary and secondary keys  back		
				if(!isComposite&&isPrimaryValues==false&&tempPrimaryValues.size()<1){%>
        <th align="center" valign="top" class="style1"> <%QuickForm.writeHtml(out,conditionKey.getName());%>
            <%}if(!conditionKey.isPassive()){
								 %>
        <th colspan=<%=colspan%> valign="top" class="style1" <%if(selection.length()>0) out.println("bgcolor=\"#009933\"");%>align="center"> <%
						  String primaryKeyName=null;
						  String secondaryKeyName = null;
						  if(compositeKeyId!=-1){
								 List primaryValues = conditionKey.getPrimaryKeyValues();
								 Iterator primaryValuesItr = primaryValues.iterator();
								 int primaryConditionKeyId = conditionKey.getPrimaryConditionKeyId();
									if(primaryConditionKeyId!=-1){
								ConditionKey primaryKey = decisionTable.getConditionKey(primaryConditionKeyId);
								primaryKeyName=primaryKey.getName();
										int secondaryConditionKeyId = conditionKey.getSecondryConditionKeyId();

								if(secondaryConditionKeyId!=-1){
									ConditionKey secondaryKey = decisionTable.getConditionKey(secondaryConditionKeyId);
									secondaryKeyName=secondaryKey.getName();
								}


							}

                          String resultString=conditionKey.getName();
								if(secondaryKeyName!=null){
									resultString=secondaryKeyName;
								}
								if(primaryKeyName!=null){
									resultString+=" ("+primaryKeyName+")";
								}

								while(primaryValuesItr.hasNext()){
								tempStringForRowHeader.append("<th align=\"center\">");
								String primaryValue = primaryValuesItr.next().toString();

	%>
            <%
							tempStringForRowHeader.append(primaryValue+"</th>");

							}%>
            <%=resultString%>
            <div align="right"><a href="CompositeKey.jsp?decisionTableId=<%=decisionTable.getId()%>&compositeKeyId=<%=compositeKeyId%>"><img src="images/dtm/preferences.png" width="16" height="16" border="0" class="borderTable"></a>
                <%}else{

						  if(selection.length()>0){
						  	tempStringForRowHeader.append("<th bgcolor=\"#009933\"></th>");
						  }else{
						  	tempStringForRowHeader.append("<th></th>");
							}
						  %>
                <%QuickForm.writeHtml(out, conditionKey.getName());%>
                <%
						  }%>
          </div></th>
        <%
						}
						}

						while(possibleSelectionsItr.hasNext()){
						 tempStringForRowHeader.append("<th bgcolor=\"#009933\"></th>");
						%>
        <th align="center" bgcolor="#009933" class="style1"><%QuickForm.writeHtml(out, possibleSelectionsItr.next().toString());%></th>
        <%
						}tempStringForRowHeader.append("</tr>");
						%>
      </tr>
      <%=tempStringForRowHeader.toString()%>
      <%

    // display input mappings table
  	String[] bcolor = {"evenrow","oddrow"};
    int nextColor = 0;
    String rowColor = bcolor[nextColor];
		//get selections
			List selections = scenario.getSelections();
   			Iterator selectionsItr = selections.iterator();
		//get conditions
			List conditions = scenario.getConditions();
   			Iterator conditionsItr = conditions.iterator();
%>
      <tr align="center" class="<%=rowColor%>" valign="top">
        <td align="center" class="style1"><%=scenario.getId()%> </td>
        <%
					//getting condition keys
					
							isPrimaryValues=false;
							isComposite=false;
							while (conditionsItr.hasNext())
							{
							Object obj = conditionsItr.next();
							Condition condition = (Condition) obj;
							String conditionValue = condition.getConditionValue();
							
							if(conditionValue==null) conditionValue="";
							ConditionKey conditionKey = decisionTable.getConditionKey(condition.getConditionKeyId());
							int compositeKeyId = -1;
							if(conditionKey.getType().equals(ConditionKey.COMPOSITE_VALUE)) {
							compositeKeyId = conditionKey.getId();
							isComposite=true;
							}
							
       
				if(!conditionKey.isPassive())isPrimaryValues=true;
				//displays primary and secondary keys  back		
				if(!isComposite&&isPrimaryValues==false&&tempPrimaryValues.size()<1){%>
        <td align="center" class="style1"><input type="text" name="ConditionValue<%=condition.getConditionKeyId()%>" value="<%=conditionValue%>"></td>
        <%}	
					
					if(!conditionKey.isPassive()){
							
				
			//sets primary and secondary values of composite keys
						  if(compositeKeyId!=-1){
								 List primaryValues = conditionKey.getPrimaryKeyValues();
								 Iterator primaryValuesItr = primaryValues.iterator();

								 int primaryConditionKeyId = conditionKey.getPrimaryConditionKeyId();
								String primaryKeyName = null;
								if(primaryConditionKeyId!=-1){
									ConditionKey primaryKey = decisionTable.getConditionKey(primaryConditionKeyId);
									primaryKeyName=primaryKey.getName();
								}
								Map compositeValues = condition.getCompositeValueList();
									
							int compositeIndex=0;
								while(primaryValuesItr.hasNext()){
								String key = primaryKeyName+"="+primaryValuesItr.next();
									String resultString = "";
									Object valueObj = compositeValues.get(key);
									if(valueObj!=null){
										resultString = valueObj.toString();
									}
									compositeIndex++;
								%>
        <td align="center" class="style1"><input type="text" name=<%="ConditionValue"+conditionKey.getId()+":"+compositeIndex%> value="<%=resultString%>" >        </td>
        <%}%>
        <%}else{
						  %>
        <td align="center" class="style1"><input type="text" name="ConditionValue<%=condition.getConditionKeyId()%>" value='<%=conditionValue%>'></td>
        <%
				}
						  
			}
			
        
		}
				//sets Selection Values
							while (selectionsItr.hasNext())
							{
							Object obj = selectionsItr.next();
							Selection selection = (Selection) obj;
							String selectionValue=selection.getSelectionValue();
							if (selectionValue==null)selectionValue="";
							%>
        <td align="center" class="style1"><input type="text" name="approval<%=selection.getId()%>" value="<%=selectionValue%>" >        </td>
        <%
							}
							%>
      </tr>
    </table></td>
  </tr>
  <tr align="center" class="oddrow">
    <td align="right" ><table border="0" cellpadding=0 cellspacing=0>
      <tr>
        <td align="right"><table border="0" cellspacing="0" cellpadding="0">
            <tr background="images/buttons/com_button_bg.gif">
              <td width="15"><img src="images/buttons/but_save.gif"></td>
              <td background="images/buttons/com_button_bg.gif" nowrap><a href="javascript:doSubmit();">
                <div align="center" class="buttonlink"> OK</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>&nbsp;</td>
        <td><table border="0" cellspacing="0" cellpadding="0">
            <tr background="images/buttons/com_button_bg.gif">
              <td width="15"><img src="images/buttons/cancel.gif"></td>
              <td background="images/buttons/com_button_bg.gif" nowrap><a href="DecisionTableDetail.jsp?decisionTableId=<%=decisionTableId%>">
                <div align="center" class="buttonlink">Cancel</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></td>
  </tr>
  </table>
<tr>
  <td>
  
</form>
</center>
</body>
</html>

