<%@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.workflow.WFSession"
%><%@page import="com.fujitsu.iflow.model.workflow.WFObjectFactory"
%><%@page import="com.fujitsu.ibpm.dtm.*"
%><%@page import="com.fujitsu.iflow.model.util.*"
%><%@page import="java.util.List"
%><%@page import="java.util.Iterator"
%><%@page import="java.util.ArrayList"
%>
<% //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" %>
    <%
    String isActiveStr    = (String) session.getAttribute("isActive");
    boolean isActive=false;
    if(isActiveStr==null)isActive = false;
    else
    isActive = new Boolean(isActiveStr).booleanValue();
    List importedDecisionTables  = new ArrayList();

    //used for whether file is opened or not
    boolean isFileLoad = false;
    List existingDecisionTables = null;
    String curretnFileName = DecisionTableManager.defaultFileName; // reads from the default file name
    if(fileNameObj!=null) curretnFileName = fileNameObj.toString();
        DecisionTableManager currentDtm = (DecisionTableManager) session.getAttribute("DecisionTableManager");
    if(currentDtm==null){
        currentDtm = new DecisionTableManager(curretnFileName,docRepository);
    }
        existingDecisionTables = currentDtm.getDecisionTables();



    //actionStr = request.getParameter("pageaction");

    String fileNameNew = request.getParameter("fileName");
    importFileName=fileNameNew;

     bps = (BPMSession) session.getAttribute("BPMSession");
     pwd = (String)session.getAttribute("password");

  if (actionStr != null && actionStr.equals("load")) {
//change start here
%>
        <jsp:useBean id="myUpload" scope="page" class="com.fujitsu.iflow.model.util.Upload" /><%

     myUpload.initialize(pageContext);
    myUpload.upload();

    UploadFile firstFile = myUpload.getFiles().getFile(0);
    String ImportedFileName = firstFile.getFilePathName();
    String fileType = firstFile.getContentType();
    String fileSubType = firstFile.getContentDisp();
   InputStream is = new JspDumbInputStream(firstFile);
        try{
            ObjectInputStream istream = new ObjectInputStream(is);
            Object obj = istream.readObject();
             importedDecisionTables = (ArrayList) obj;
            istream.close();
            is.close();
        }catch(Exception ex){
            ex.printStackTrace();
            throw new Exception("Error loading Decision Tables from file: "+ImportedFileName);
        }
        session.setAttribute("NewDecisionTables",importedDecisionTables);
isFileLoad=true;
    }
%>


<html>
<head><title>Interstage Business Process Manager | Import  DecisionTables</title>
<LINK rel="stylesheet" href="styles/dtm.css" type="text/css">
<!--<script type="text/javascript" language="javascript" src="jscript/check.js"> </script>-->
<script language="javascript" src="styles/clockscripts.js"></script>

<script language="javascript">
var fileName;
function validateFields()
{
    if (document.dtmForm.fileName.value == "")
    {
        alert("Please enter a valid file path.");
        document.dtmForm.fileName.focus();
        return false;
    }
    //popups a window if the imported file is any other file(i.e., other than ".dat" file)
    var isValidFile="valid";
    if(document.dtmForm.fileName.value.lastIndexOf(".dat")<0)isValidFile="invalid";
    if(document.dtmForm.fileName.value.lastIndexOf(".DAT")>0){
        isValidFile="valid";
    }
    if(isValidFile=="invalid"){
         alert("Please enter a valid file name.");
         document.dtmForm.fileName.focus();
          return false;
    }
    fileName=document.dtmForm.fileName.value;
}
function doSubmit(){

    document.main.selectedName.value="";
    var selectedDT = document.main.selectedName;
    var frm = document.main;
        for(i=0;i< frm.length;i++)
        {
            e=frm.elements[i];
            if(e.type=='checkbox')
            {
               if (e.checked)
                {
                    selectedDT.value+=e.name+"&sep;";
                }
            }
        }

    document.main.pageaction.value = "importDecisionTableManager";

    document.main.submit();
}
</script>

</head>
<body class="bodyClass" onLoad="goforit();">
<jsp:include page="DTMHeader.jsp" flush="true"/><br/>
<br/><br/>
<form name="dtmForm" enctype="multipart/form-data" method="post" action="ImportDecisionTable.jsp?pageaction=load" onSubmit="return validateFields()">
<input type='hidden' name="showTable" value="true" />
<input name="pageaction" type="hidden" id="pageaction" value="load">
<center>
<TABLE width="80%" border="0" align="center" cellpadding="4" cellspacing="1" bgcolor="#CCCCCC" class="tableClass">
    <tr>
        <td style="filter:progid:DXImageTransform.Microsoft.Gradient(startColorStr='#FFFFFF', endColorStr='#6699CC', gradientType='1'"><b>Load
          Decision Tables File</b></td>
    </tr>
    <tr>
            <td bgcolor="#FFFFFF" align="center"><br/>
            Decision Tables File:

             <input type="file" name="fileName" width="300" size="50" >
 <br/>
          <br/>            </td>
    </tr>
    <tr>
        <td valign="middle" align="center" bgcolor="#EEEEEE"><input name="submit" type="submit" class="submitClass" value="Load Decision Tables File" /></td>
    </tr>
</table>
</center></form>

<div align="center"><br>
<br>
<%
    if(isFileLoad){%>

<form name="main" method="post" action="DecisionTableManagement.jsp" >


                <div align="center">
                  <TABLE bgcolor="#CCCCCC" border="0" cellpadding="4" cellspacing="1" class="tableClass" width="80%" 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">
                        Decision Tables

                        </font>
                          <div align="right"></div>
                          </div>                      </td>
                    </tr>
                    </table>
                  <TABLE bgcolor="#CCCCCC" border="0" cellpadding="4" cellspacing="1" class="tableClass" width="80%" align="center">
                    <tr align="center" class="headrow" bgcolor="#0066CC">
                      <th align="center" width="10%">Import</th>
                    <th> Name </th>
                    <th width="60%"> Description</th>
                 <th align="center" width="10%"> Status</th>

                </tr>
  <%
     String[] bcolor = {"evenrow","oddrow"};
    int nextColor = 0;
    String rowColor = bcolor[nextColor];
    int decisionTableIndex = 0;
           Iterator importedDecisionTablesItr = importedDecisionTables.iterator();

        while (importedDecisionTablesItr.hasNext())
        {
            DecisionTable decisionTable = (DecisionTable) importedDecisionTablesItr.next();
           // debug(trace, out, "\n certeria="+decisionTable.toString());
            int isDuplicate=checkExistDecisionTable(decisionTable,existingDecisionTables);

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


%>
                    <tr align="center" class="<%=rowColor%>" valign="top">
                      <td width="10%" align="center">
                      <input <%if(isDuplicate==0) out.println(" disabled "); %>type="checkbox" name="<%QuickForm.writeHtml(out,decisionTable.getName());%>" <%if(isDuplicate==1) out.println(" checked "); %>  value=<%QuickForm.writeHtmlWithNBSPs(out, decisionTable.getName());%>  />                  </td>
                      <td width="20%"><% if(isDuplicate==0){%><font color="#CCCCCC"><%}QuickForm.writeHtmlWithNBSPs(out, decisionTable.getName()); %></font></td>
                      <td width="60%"><%if(isDuplicate==0){%><font color="#CCCCCC"><%}QuickForm.writeHtml(out, decisionTable.getDescription());%></font></td>

                <td align="center"><%if(isDuplicate==0){%>Duplicate<%}else{%>New<%}%></td>
                </tr>
  <%
decisionTableIndex++;
    }
%>
                                </TABLE>
                </div>

  <table border="0" align="center" cellpadding=0 cellspacing=0>
    <tr>
      <td align="right">&nbsp;</td>
      <td>&nbsp;</td>
    </tr>
    <tr>
      <td align="right"><input type="hidden" name="importedFileName" />
      <table border="0" cellspacing="0" cellpadding="0">
            <tr background="images/buttons/com_button_bg.gif">
              <td nowrap>
               <input  type="hidden" name="selectedName">
               <input name="pageaction" type="hidden" id="pageaction">
            <input type="button" value="Load Decision Tables" class="core-button" onClick="doSubmit()" />  </td>

            </tr>
       </table>       </td>
      <td><table border="0" cellspacing="0" cellpadding="0">
          <tr background="images/buttons/com_button_bg.gif"> </tr>
      </table></td>
    </tr>
  </table>
</form>
  <% }%>
  <br>

</body>
</html>
<%!
 BPMSession bps = null;
 String pwd = "";
// checks for duplicate decision table upon import decision table
    public
    int
    checkExistDecisionTable(DecisionTable importedDecisionTable,List existedDecisionTables) throws Exception
    {
        int flag=1;
        Iterator existedDecisionTablesItr = existedDecisionTables.iterator();

        while(existedDecisionTablesItr.hasNext()){
            DecisionTable existedDecisionTable=(DecisionTable)existedDecisionTablesItr.next();
                if(importedDecisionTable.getName().equals(existedDecisionTable.getName())){
                    flag=0;
                    break;
                }
        }
        return flag;
    }
    String importFileName="";
%>

<%!

    class JspDumbInputStream extends InputStream
    {

        UploadFile attachment;
        int pointer = 0;
        int fileSize = 0;

        public
        JspDumbInputStream(UploadFile dumbFile)
        {
            attachment = dumbFile;
            pointer = 0;
            fileSize = dumbFile.getSize();
        }

        public
        int
        read()
        {
            if (pointer >= fileSize) {
                return -1;
            }
            return (attachment.getBinaryData(pointer++) & 255);
        }
    }

    public
    void
    copyInputToFile(InputStream is, String fileName)
        throws Exception
    {
        File outFile = new File(fileName);
        OutputStream os = new FileOutputStream(outFile);

        int byteBuf = is.read();
        while (byteBuf >= 0)
        {
            os.write(byteBuf);
            byteBuf = is.read();
        }

        os.flush();
        os.close();
    }

%>
