<%@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.StringTokenizer"
%><%@page import="java.util.Enumeration"
%><%@page import="java.text.DateFormat"
%><%@page import="com.fujitsu.ibpm.dtm.*"
%><%@page import="com.fujitsu.ibpm.dtm.engine.*"
%><%@page import="com.fujitsu.ibpm.dtm.engine.datamatch.*"
%>
<%-- 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" %>
 <%-- Sets the Audit Result --%>
 <%@ include file="setAuditResult.jsp" %>
<%
String displayWarningStr="";
%>
<html>
<head>
<title>Interstage Business Process Manager | DecisionTable Testing </title>
<link href="styles/dtm.css" rel="stylesheet" type="text/css">
<script>
function checkUda(displayWarning)
{
    if(displayWarning=="Please set User Defined Attribute")
    {
     alert("Please set User Defined Attribute in the mapping page.");
     document.location.href="DecisionTableDetail.jsp?decisionTableId=<%=decisionTableId%>";
    }
}
</script>
<style type="text/css">
<!--
.style1 {
    color: #FFFFFF;
    font-weight: bold;
}
.style2 {font-size: 12px; font-weight: bold; font-family: Verdana, Arial, Helvetica, sans-serif;}
-->
</style>
</head>

<body class="bodyClass">
<center>
<jsp:include page="DTMHeader.jsp" flush="true"/><br/>

<form name="main" method="post" action="DecisionTableTest.jsp?pageaction=runDecisionTableTest&decisionTableId=<%=decisionTableId%>" >

    <table bgcolor="#CCCCCC" border="0" cellpadding="4" cellspacing="1" class="tableClass" width="95%" align="center">

      <tr align="center" class="headrow">
        <td bgcolor="#ffffff"  align="right">
           <table border="0" cellspacing="0" cellpadding="0"  align="right">
            <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>
              <% isActiveStr =(String)session.getAttribute("isActive");
                 if(isActiveStr!=null)
                 {
                         isActive = new Boolean(isActiveStr).booleanValue();
                 }%>
              <a href="DecisionTableDetail.jsp?decisionTableId=<%=decisionTableId%>&isActive=<%=!isActive%>">
                <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><table border="0" cellspacing="0" cellpadding="0">
            <tr background="images/buttons/com_button_bg.gif">
              <td width="15"><img src="images/buttons/but_start.gif" width="21" height="24"></td>
              <td background="images/buttons/com_button_bg.gif" nowrap> <a href="javascript:main.submit();">
                <div align="center" class="buttonlink"> Test DecisionTable</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>
      <tr align="center" class="headrow">
        <td bgcolor="#EEEEEE" style="filter:progid:DXImageTransform.Microsoft.Gradient(startColorStr='#FFFFFF', endColorStr='#6699CC', gradientType='1')" align="right">
          <div align="left"><font color="#000000" size="2"> Decision Table:
              <%QuickForm.writeHtmlWithNBSPs(out, decisionTable.getName()); %>
            <div align="right"></div>
            </font></div>
        </td>
      </tr>
    </table>
    <br>
    <table bgcolor="#CCCCCC" width="95%" border="0" cellpadding="2" cellspacing="1" align="center" class="tableclass">

      <tr class="oddrow">
        <td valign="top" width="200"><b>Description</b>:</td>
        <td valign="top">
          <textarea name="decisionTableDescription" readonly="readonly" cols="80" rows="4"><%=decisionTable.getDescription()%></textarea>        </td>
      </tr>
     </table>

   <br>
    <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')" align="right"><div align="left"><font color="#000000" size="2"><font color="#000000">Conditions:</font></font></div></td>
      </tr>
    </table>
    <table bgcolor="#CCCCCC" border="0" cellpadding="4" cellspacing="1" class="tableClass" width="95%" align="center">
      <tr align="center" class="headrow" bgcolor="#0066CC">
        <th align="center"> Id</th>
        <th> Name</th>
        <th> Description</th>
        <th> User Defined Attribute</th>
        <th align="center"> Value </th>
      </tr>
      <%
    // display input mappings table
      List mappings = decisionTable.getMappings();
    Iterator itr = mappings.iterator();
       String[] bcolor = {"evenrow","oddrow"};
    int nextColor = 0;
    String rowColor = bcolor[nextColor];
    int mapId=0;
          while (itr.hasNext())
        {
            Mapping mapping = (Mapping) itr.next();
            debug(trace, out, "\n mapping="+mapping.toString());
            ConditionKey  cKey = decisionTable.getConditionKey(mapping.getName());
            if(!cKey.isComposite()){
             rowColor = bcolor[nextColor];
            nextColor = (nextColor + 1)%2;


%>
      <tr align="center" class="<%=rowColor%>" valign="top">
        <td align="center"><%=++mapId%> </td>
        <td width="20%"><%=mapping.getName()%> </td>
        <td width="30%"><%=mapping.getDescription()%> </td>
        <td width="20%"><%
                // displaying data field references
                        StringBuffer displayString=new StringBuffer();
                        Iterator dataReferencesItr = mapping.getDataFieldReferences().iterator();
                        int index=0;
                        while(dataReferencesItr.hasNext()){
                            if(index++!=0) displayString.append(",");
                            displayString.append((String)dataReferencesItr.next());
                        }
                        // if no data field references then display warning message
                        if (displayString.length()<1)
                        {
                            displayWarningStr="Please set User Defined Attribute";
                            %>
                            <script  type="text/javascript">
                                 checkUda('<%=displayWarningStr%>');
                            </script>
                            <font color="#FF0000"><%=displayWarningStr%></font>
                        <%}
                        else
                        {displayWarningStr="";
                        %>
                            <%QuickForm.writeHtmlWithNBSPs(out, displayString.toString());%>
                        <%}%></td>
        <td width="20%" align="center"><%
    // displaying input values of corresponding data field references
                List dataReferences = mapping.getDataFieldReferences();
                if(dataReferences.size()>0){
                    String name = dataReferences.get(0).toString();
                    String value = request.getParameter(name);

                    if(value==null) value="";
        %>
            <input type="text" name="<%=name%>" value="<%=value%>">
            <%}
    // displaying value mappings
                        displayString=new StringBuffer();
                        Iterator valueMappingsItr = mapping.getValueMappings().keySet().iterator();
                        index=0;
                        while(valueMappingsItr.hasNext()){
                            if(index++!=0) displayString.append(",");
                            String key = (String)valueMappingsItr.next();
                            displayString.append(key);
                            displayString.append("=");
                            displayString.append(mapping.getValueMappings().get(key).toString());
                        }
                        %>
          <br>
          <%QuickForm.writeHtml(out, displayString.toString());%>
            <font color="#000000" size="2"> </font></td>
      </tr>
      <%
    }
    }
%>
    </table>
    <p><br>


    </p>
    <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')" align="right">
          <div align="left"><font color="#000000" size="2"> Results:</font></div>
        </td>
      </tr>
    </table>
    <table bgcolor="#CCCCCC" border="0" cellpadding="4" cellspacing="1" class="tableClass" width="95%" align="center">
      <tr align="center" class="headrow" class="resultHeader">
        <th align="center" class="resultHeader"> Id</th>
        <th class="resultHeader"> Name</th>
        <th class="resultHeader"> Description</th>
        <th class="resultHeader">User Defined Attribute</th>
        <th align="center" class="resultHeader"><span class="style1">Test
        Result</span></th>
      </tr>
      <%
 // display result mappings table
      mappings = decisionTable.getResultMappings();
    itr = mappings.iterator();
       String[] bgcolor = {"evenrow","oddrow"};

    nextColor = 0;
    rowColor = bgcolor[nextColor];

    int resultIndex=-1;
          while (itr.hasNext())
        {
            Mapping mapping = (Mapping) itr.next();
            debug(trace, out, "\n mapping="+mapping.toString());

            rowColor = bgcolor[nextColor];
            nextColor = (nextColor + 1)%2;


%>
      <tr align="center" class="<%=rowColor%>" valign="top">
        <td align="center"><%=mapping.getResultId()%> </td>
        <td width="20%"><%=mapping.getResultName()%> </td>
        <td width="30%"><%=mapping.getResultDescription()%> </td>
        <td width="20%">
          <%
          // displaying data field references
                        StringBuffer displayString=new StringBuffer();
                        Iterator dataReferencesItr = mapping.getResultDataFieldReferences().iterator();
                        int index=0;
                        while(dataReferencesItr.hasNext()){
                            if(index++!=0) displayString.append(",");
                            displayString.append((String)dataReferencesItr.next());
                        }
                        // if no uda then display warning message
                        if (displayString.length()<1)
                        {
                            displayWarningStr="Please set User Defined Attribute";

                            %><script  type="text/javascript">
                                 checkUda('<%=displayWarningStr%>');
                            </script>
                            <font color="#FF0000"><%=displayWarningStr%></font>
                        <%}
                        else
                        {displayWarningStr="";
                        %>
                            <%QuickForm.writeHtmlWithNBSPs(out, displayString.toString());%>
                        <%}%>
           </td>
        <td width="20%" align="center">
        <%
                   if(result==null)
                      auditRes="";
                else
                {
                    if(result.size()>0)
                        auditRes=(String)result.get(++resultIndex);
                    else
                        auditRes="";
                }
         %>
          <b><font color="#006633"><%=auditRes %></font></b> <font color="#000000" size="2"> </font></td>
      </tr>
      <%}%>
    </table>
    <br>
    <%if(isResult){%>
    <table bgcolor="#CCCCCC" border="0" cellpadding="4" cellspacing="1" class="tableClass" width="95%" align="center">
         <tr align="center" class="resultrow" valign="top">
        <td bgcolor="#ffffff"  align="left"><span class="titletext"><b></b></span><span class="style2"><b>Test
          Audit:</b></span></td>
        <td bgcolor="#ffffff"  align="left"><font  color="#000000"><%=auditData%></font></td>
      </tr>
    </table>
    <br>

      <%}%>

    <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')" align="right">
          <div align="left"><font color="#000000" size="2"> Decisions:</font>          </div>
        </td>
      </tr>
    </table>
    <table bgcolor="#CCCCCC" border="0" cellpadding="4" cellspacing="1" class="tableClass" width="95%" align="center">
      <tr align="center" class="headrow" bgcolor="#0066CC" valign="top">

        <th align="center"> #</th>
              <%
                        //calculates the length of the Condition cell's length in case of normal and composite conditions
                           int totalIsPassiveConditions = 0;
                           int totalConditions = 0;
                        String printCondition="Conditions";
                        int totalCompConditions=0;
                        int totalPrimaryKeyValues=0;
                        int totalCompositeKeyWithValues=0;
                        boolean cmpExists= false;
                        List PrimaryValuesList = new ArrayList();
                        conditionKeysItr = conditionKeys.iterator();
                        while(conditionKeysItr.hasNext()){
                        ConditionKey conditionKey = (ConditionKey) conditionKeysItr.next();
                            if(conditionKey.isPassive())totalIsPassiveConditions++;
                            if(conditionKey.getType().equals(ConditionKey.COMPOSITE_VALUE)) {
                                    totalCompConditions++;
                                PrimaryValuesList = conditionKey.getPrimaryKeyValues();
                                if(PrimaryValuesList.size()>0) {
                                    totalCompositeKeyWithValues++;
                                    totalPrimaryKeyValues+=PrimaryValuesList.size();
                                }
                                cmpExists=true;
                            }
                    }

                    conditionKeysItr = conditionKeys.iterator();
                        if(cmpExists && totalPrimaryKeyValues>0 && totalCompConditions>=2)
                            totalConditions=conditionKeys.size()+totalPrimaryKeyValues-totalIsPassiveConditions-totalCompositeKeyWithValues;
                        else if(totalCompositeKeyWithValues<2)
                            totalConditions=conditionKeys.size()+totalPrimaryKeyValues-totalCompositeKeyWithValues*3;

                        //displays if there is no conditions
                        if (conditionKeys.size()<1){printCondition="Conditions"; %>
                       <td colspan=<%=conditionKeys.size()%> align="center" class="conditioncell" ><%=printCondition%></td>
                       <%}

                        if (conditionKeys.size()>0){printCondition="Conditions"; %>
                       <td colspan=<%=totalConditions%> align="center" class="conditioncell"><%=printCondition%></td>
                       <%}

                    String printSelection="Results";
                    //displays if there is no results
                    if (possibleSelections.size()<1){printSelection="Results"; %>
                       <td  colspan=<%=possibleSelections.size()%> align="center" class="selectioncell"><%=printSelection%></td>
                       <%}

                        if (possibleSelections.size()>0){printSelection="Results"; %>
                       <td  colspan=<%=possibleSelections.size()%> align="center" class="selectioncell"><%=printSelection%></td>
                       <% }%>
                     </tr>
                     <%
                        if( conditionKeys.size()>0 || possibleSelections.size()>0)
                        {%>
                     <tr align="center" class="headrow" bgcolor="#0066CC" valign="top">

                       <th align="center" width="30">&nbsp;</th>
                       <%}%>
                       <%
                     //displays if there is no conditions
                     if(!(possibleSelections.size()<1 && conditionKeys.size()<1)){
                        if (conditionKeys.size()<1){%>
                       <td colspan=<%=conditionKeys.size()%> align="center" class="conditioncell" >&nbsp;</td>
                       <%}}

        // displays Scenario Table
                         StringBuffer tempStringForRowHeader = new StringBuffer();
                         tempStringForRowHeader.append("<tr align=\"center\" class=\"headrow\" bgcolor=\"#0066CC\" valign=\"top\"> <th align=\"center\"> </th>");

                        while(conditionKeysItr.hasNext()){
                        ConditionKey conditionKey = (ConditionKey) conditionKeysItr.next();
                        String selection = "";
                        int compositeKeyId = -1;
                        if(conditionKey.getType().equals(ConditionKey.COMPOSITE_VALUE)) {
                            compositeKeyId = conditionKey.getId();
                        }
                        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()){
                                 %>
        <th colspan=<%=colspan%> <%if(selection.length()>0) out.println("bgcolor=\"#009933\"");%> align="center" valign="top">

          <%
          // gets primary and secondary values
                          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+")";
                                }
                //displays primary values
                                while(primaryValuesItr.hasNext()){
                                tempStringForRowHeader.append("<th align=\"center\">");
                                String primaryValue = primaryValuesItr.next().toString();

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

                            }
                             //displays if there is no results but composit conditions
                          if (possibleSelections.size()<1){
                        tempStringForRowHeader.append("<th bgcolor=\"#009933\">&nbsp;</th>");}

                            %>
          <%=resultString%>
          <div align="right">
            <%}else{
                     if(selection.length()>0){
                              tempStringForRowHeader.append("<th bgcolor=\"#009933\"></th>");
                          }else{
                              tempStringForRowHeader.append("<th></th>");
                            }
                          %>
            <%=conditionKey.getName()%>
            <%
                          }%>
          </div>
        </th>
        <%
                        }
                        }

                        //displays if there is no result
                        if(!(possibleSelections.size()<1 && conditionKeys.size()<1)){
                        if (possibleSelections.size()<1){%>
                       <td colspan=<%=possibleSelections.size()%> align="center" bgcolor="#009933">&nbsp;</td>
                       <%}}


            //displays selections
                        while(possibleSelectionsItr.hasNext()){
                        String temp = possibleSelectionsItr.next().toString();
                          tempStringForRowHeader.append("<th bgcolor=\"#009933\"></th>");
%>
        <th  bgcolor="#009933" align="center"> <%=temp%></th>
                        <%}%>

      </tr>
      <%=tempStringForRowHeader.toString()%>
      <%

  // display input mappings table
      List scenarios = decisionTable.getScenarios();
     itr = scenarios.iterator();
         while (itr.hasNext())
        {
            Scenario scenario = (Scenario) itr.next();
            debug(trace, out, "\n scenario="+scenario.toString());
             rowColor = bgcolor[nextColor];
            nextColor = (nextColor + 1)%2;
        //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"> <%=scenario.getId()%> </td>
        <%
             if (conditionKeys.size()<1){%>
                       <td colspan=<%=conditionKeys.size()%> align="center" >&nbsp;</td>
                       <%}


                            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());
                    if(!conditionKey.isPassive()){
                            int compositeKeyId = -1;
                            if(conditionKey.getType().equals(ConditionKey.NUMBER_VALUE)) {
                                String operator = NumericDataMatch.getNumericOperator(conditionValue);
                                if (operator == null && !conditionValue.equals("")) {
                                    conditionValue = NumericDataMatch.DEFAULT_OPERATOR + conditionValue;
                                }
                            }
                            if(conditionKey.getType().equals(ConditionKey.COMPOSITE_VALUE)) {
                            compositeKeyId = conditionKey.getId();
                            }
                            %>
        <%
                          if(compositeKeyId!=-1){
                                 List primaryValues = conditionKey.getPrimaryKeyValues();
                                 if(primaryValues.size()==0){%>
        <td align="center"> </td>
        <%}


                                 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();

                                while(primaryValuesItr.hasNext()){
                                String key = primaryKeyName+"="+primaryValuesItr.next();
                                    String resultString = "";
                                    Object valueObj = compositeValues.get(key);
                                    if(valueObj!=null){
                                        resultString = valueObj.toString();
                                    }
                                %>
        <td align="center"> <%=resultString%> </td>
        <%}%>
        <%}else{
                          %>
        <td align="center"> <%=conditionValue%></td>
        <%}}%>
        <%
                            }

                //displays if there is no results
                            if (possibleSelections.size()<1){%>
                       <td colspan=<%=possibleSelections.size()%> align="center">&nbsp;</td>
                       <%}



                //displays Selection Values
                            while (selectionsItr.hasNext())
                            {
                            Object obj = selectionsItr.next();
                            Selection selection = (Selection) obj;
                            String selectionValue=selection.getSelectionValue();
                            if(selectionValue==null)selectionValue="";
                            %>
        <td align="center">
          <%=selectionValue%>
        </td>
        <%}%>
      </tr>
      <%}%>
    </table>
    <p><br>
      <br>
    </p>
    <br>
    <p>&nbsp;</p>
  </form>
</center>
</body>
</html>
<%!
  public
    boolean
    isInteger(
        String text)
    {
        boolean isMatch = false;
        if (text != null && text.trim().length()>0)
        {
            try
            {
                Double i = Double.valueOf(text);
                isMatch = true;
            }
            catch(NumberFormatException e)
            {
                isMatch = false; //unnecessary
            }
        }
        return isMatch;
    }

    public
    boolean
    isBoolean(
        String text)
    {
        boolean isMatch = false;
        if (text != null && text.trim().length()>0)
        {
            if (text.trim().equalsIgnoreCase("true") ||
                text.trim().equalsIgnoreCase("false"))
            {
                isMatch = true;
            }
        }
        return isMatch;
    }

%>