<%-- This code is used in DecisionTableManagement.jsp file
 Sets when move up, move down, view active DecisionTable, enable DecisionTable, save DecisionTable, request approval, apply changes, import DecisionTable --%>
<%@page import="java.util.*" 
%><%@page import="java.io.*" 
%><%@page import="com.fujitsu.ibpm.dtm.*"
%><%@page import="com.fujitsu.iflow.model.workflow.*"
%><%@page import="com.fujitsu.iflow.model.bpm.BPMSession"
%><%@page import="com.fujitsu.iflow.model.bpmcore.BPMSessionImpl"
%><%@page import="com.fujitsu.iflow.model.wfadapter.DocRepository"
%>
<%@ include file="sortProcessDefinition.jsp" %>

<%
	boolean trc=false;
	BPMSession bpsSession = (BPMSession) session.getAttribute("BPMSession");
	String password = (String)session.getAttribute("password");
	String actionString = request.getParameter("pageaction");
	DecisionTableManager dtmMgr = (DecisionTableManager) session.getAttribute("DecisionTableManager");
	String decisionTableDefaultFileName = DecisionTableManager.defaultFileName; 
    String decisionTableIdStr = request.getParameter("decisionTableId");
     String editUrl = "DecisionTableDetail.jsp";

String tableTitle = "Active Decision Tables";

boolean isEditable = false;
boolean isActive = true;             //used to check whether the DecisionTable is active or not
boolean toBeSaved = false;              //used for saving the DecisionTable
boolean toBeApproved = false;          //used for checking whether the DecisionTable is approved or not

String isActiveStr = (String) session.getAttribute("isActive");
String isEditableStr = (String) session.getAttribute("isEditable");

boolean isImport=false;
String toBeSavedStr = (String) session.getAttribute("toBeSaved");
toBeSaved=new Boolean(toBeSavedStr).booleanValue();

String docRoot = application.getRealPath("/").trim();
if (docRoot.endsWith(File.separator))
    docRoot = docRoot + "attachments";
else
docRoot = docRoot + File.separator + "attachments";

//this is used for creating dtm.dat and activeDtm.dat in server attachment folder
//saving the dtm.dat file
String strFilename = decisionTableDefaultFileName.substring(decisionTableDefaultFileName.lastIndexOf("/")+1,decisionTableDefaultFileName.length());
//strFilename=strFilename.toUpperCase();
String clientPath = docRoot + File.separator + strFilename;
clientPath=replaceWithBackSlashLocal(clientPath);
WFSession wfSes = ((BPMSessionImpl)bpsSession)._wfs;
DocRepository docRep= getDocRepositoryLocal(wfSes,password);
if(dtmMgr==null){
		dtmMgr = new DecisionTableManager(DecisionTableManager.activeFileName,docRep);
	}
createDocumentLocal(docRep,clientPath,DecisionTableManager.defaultFileName);
//saving the activeDtm.dat file
String strActiveFileName = DecisionTableManager.activeFileName.substring(DecisionTableManager.activeFileName.lastIndexOf("/")+1,DecisionTableManager.activeFileName.length());
//strActiveFileName=strActiveFileName.toUpperCase();
clientPath = docRoot + File.separator + strActiveFileName;
clientPath=replaceWithBackSlashLocal(clientPath);
createDocumentLocal(docRep,clientPath,DecisionTableManager.activeFileName);


if(isActiveStr==null){isActive = true; isEditable=false;}
else{
    isActive = new Boolean(isActiveStr).booleanValue();
    isEditable=isActive;
}



if (actionString != null && actionString.length() > 0) {
                     toBeSaved = true;

        if (actionString.equals("saveDecisionTable")) {

                    debugLcl(trc, out, "\n action=saveDecisionTable");
                    DecisionTable decisionTable= null;
                    String name = request.getParameter("decisionTableName");
                    String type = DecisionTable.MIN_CONSTRAINT;

                    String dupDecisionTable="";
                    boolean isEdit=true;

                    //decision table for editing purpose
                    if(decisionTableIdStr!=null && decisionTableIdStr.length()>0){
                        int decisionTableId = (new Integer(decisionTableIdStr)).intValue();
                        decisionTable = dtmMgr.getDecisionTable(decisionTableId);

                        //check for duplicate decision table
                        List decisionTableList=dtmMgr.getDecisionTables();
                        Iterator decisionTableListItr=decisionTableList.iterator();
                        while(decisionTableListItr.hasNext()){
                        DecisionTable tempDecisionTable=(DecisionTable)decisionTableListItr.next();
                            if(decisionTableId!=tempDecisionTable.getId()){
                                if(tempDecisionTable.getName().equals(name)){
                                dupDecisionTable=tempDecisionTable.getName();
                                isEdit=false;
                                }
                            }
                            else {
                                if(tempDecisionTable.getName().equals(name)){
                                dupDecisionTable="";
                                isEdit=true;
                                }
                            }
                        }

                        if(!dupDecisionTable.equals(""))throw new Exception("Decision Table: "+dupDecisionTable+" already exists");

                    }else{// new decision table

                        //check for duplicate decision table
                        isEdit=false;
                        List decisionTableList=dtmMgr.getDecisionTables();
                        Iterator decisionTableListItr=decisionTableList.iterator();
                        while(decisionTableListItr.hasNext()){
                        DecisionTable tempDecisionTable=(DecisionTable)decisionTableListItr.next();
                            if(tempDecisionTable.getName().equals(name)){
                                dupDecisionTable=tempDecisionTable.getName();
                                break;
                            }
                        }

                        if(!dupDecisionTable.equals(""))throw new Exception("Decision Table: "+dupDecisionTable+" already exists");

                        if(dupDecisionTable.equals("")){//if new decision table

                        decisionTable = new DecisionTable(-1,name,type);
                        decisionTable.setDescription(request.getParameter("decisionTableDescription"));
                          dtmMgr.saveDecisionTable(decisionTable); // saves DecisionTable
                        }
                     }

                if(isEdit==true){// if existing decision table
                decisionTable.setName(name);
                decisionTable.setType(type);
                decisionTable.setDescription(request.getParameter("decisionTableDescription"));
                  dtmMgr.saveDecisionTable(decisionTable); // saves DecisionTable
                }
        }     else if (actionString.equals("reviewDecisionTable")) {
            String fileNameStr = request.getParameter("FileName");
            if(fileNameStr==null) decisionTableDefaultFileName =  DecisionTableManager.defaultFileName;
            else decisionTableDefaultFileName = fileNameStr;
            dtmMgr = new DecisionTableManager(decisionTableDefaultFileName,docRep);
            toBeSaved = false;

        }     else if (actionString.equals("viewActive")) {

             dtmMgr = new DecisionTableManager(DecisionTableManager.activeFileName,docRep);

             isActive = false;
             isEditable=true;
             toBeSaved = false;
             toBeApproved = false;
     }     else if (actionString.equals("editDecisionTables")) {
            dtmMgr = new DecisionTableManager(decisionTableDefaultFileName,docRep);
             //checks whether the file is locked by any user in database
             //if locked and any other user tries to edit then throws error
             try{
                     docRep.checkOut(decisionTableDefaultFileName.trim(),false);
                }
                catch(Exception e)
                {
                    throw new Exception("You can not Manage Decision Tables as decision tables are being used by another user. Please try again later.");
                }

              //if(!isActive)
             isActive = true;
             isEditable=false;
                toBeSaved = false;
                toBeApproved = false;
      }     else if (actionString.equals("editDecisionTable")) {
             dtmMgr = new DecisionTableManager(decisionTableDefaultFileName,docRep);
             if(isActive)
             isActive = false;
              isEditable=false;
                toBeSaved = false;
                toBeApproved = false;
      }else if (actionString.equals("moveUp")) {
                    int decisionTableId = (new Integer(decisionTableIdStr)).intValue();
                      dtmMgr.chengeDecisionTableSequence(decisionTableId,-1);

        }     else if (actionString.equals("moveDown")) {
                    int decisionTableId = (new Integer(decisionTableIdStr)).intValue();
                      dtmMgr.chengeDecisionTableSequence(decisionTableId,1);

       }     else if (actionString.equals("enableDecisionTable")) {
                    int decisionTableId = (new Integer(decisionTableIdStr)).intValue();
                      dtmMgr.changeDecisionTableEnable(decisionTableId);

         }     else if (actionString.equals("saveDecisionTableManager")) {
                    dtmMgr.setFileName(DecisionTableManager.defaultFileName);
                      dtmMgr.saveDecisionTableManager();
                    isActive=true;
                    toBeSaved = false;
                    toBeApproved = true;

   }     else if (actionString.equals("requestApprovalToDecisionTableManager")) {
                    toBeSaved=false;
                    toBeApproved=false;
                    //int pdId = -1;

                    String pdName=DecisionTableConfig.getString("ApprovalProcessDefinitionName");


                    if(pdName!=null && pdName.length()==0)//{
                        throw new Exception("Please set valid ApprovalProcessDefinitionName in dtmconfig.properties");                    
                    long pdId = getProcessDefinitionLatestIdLocal(wfSes,pdName);
                    
                    if(pdId==-1)//{
                        throw new Exception("Unable to get process definition ("+pdName+"). Please contact system administrator");

                ProcessInstantiator processInstantiator = bpsSession.getProcessInstantiator(pdId);


            //set new process data values
                    DataItem data[] = processInstantiator.getDataItems();
                    String udaApprovalReq = "ApprovalRequest";
                    if (data != null && data.length > 0) {
                        for (int i = 0; i < data.length; i++) {
                            if (udaApprovalReq.equals(data[i].getName())) {
                                Properties dataProp  = new Properties();
                                dataProp.put(udaApprovalReq,
                                    "DecisionTableManagement.jsp?action=reviewDecisionTable&FileName="
                                            + decisionTableDefaultFileName);
                                processInstantiator.setDataItemValues(dataProp);
                            }
                        }
                    }

                    processInstantiator.startNewProcess();

  }     else if (actionString.equals("applyChangesToDecisionTableManager")) {
                      docRep.checkOut(DecisionTableManager.activeFileName,false);
                      dtmMgr.applyChangesToDecisionTableManager(DecisionTableManager.activeFileName);
                    createDocumentLocal(docRep,clientPath,DecisionTableManager.activeFileName);
                    isActive=false;
                    toBeSaved=false;
                    toBeApproved=false;

       } else if (actionString.equals("importDecisionTableManager")) {

       Object newDTMObj = session.getAttribute("NewDecisionTables");
       ArrayList newDTM =(ArrayList) newDTMObj;

       List decisionTables = new ArrayList();
       String selectedDtm = request.getParameter("selectedName");

        if(selectedDtm.length()>0)
        selectedDtm=selectedDtm.substring(0,selectedDtm.lastIndexOf("&sep;"));

        if(    selectedDtm!=null){
               String[] selectedDTs=selectedDtm.split("&sep;");
               int selecDTMIndex=-1;
               decisionTables = dtmMgr.getDecisionTables(); //Returns all DecisionTables
             for(int selectedIndex=0;selectedIndex<selectedDTs.length;selectedIndex++){
                 Iterator newDTMItr= newDTM.iterator();
                   while(newDTMItr.hasNext()){
                        DecisionTable decisionTable = (DecisionTable) newDTMItr.next();
                        if(decisionTable.getName().trim().equals(selectedDTs[selectedIndex].trim())){
                            Iterator decisionTableItr = decisionTables.iterator();
                            List newdecisionTables = new ArrayList();
                            int id = -1;
                            while (decisionTableItr.hasNext()) {
                                DecisionTable dat = (DecisionTable) decisionTableItr.next();
                                if (dat.getId() > id)
                                    id = dat.getId();
                                }
                            decisionTable.setId(++id);
                            decisionTables.add(decisionTable);
                           }
                       }
              }
        }
        session.setAttribute("DecisionTableManager",dtmMgr);
    }

 }
 if(isActive) tableTitle = "Decision Tables";

 session.setAttribute("FileName",decisionTableDefaultFileName);
 session.setAttribute("DecisionTableManager",dtmMgr);
 session.setAttribute("isActive",""+isActive);
 session.setAttribute("isEditable",null);
 session.setAttribute("toBeSaved",""+toBeSaved);
 session.setAttribute("toBeApproved",""+toBeApproved);
 // display DecisionTable table
 debugLcl(trc, out, "begin display DecisionTable table");
 List decisionTables = dtmMgr.getDecisionTables(); //Returns all DecisionTables

 %>
 
 <%!
 private String replaceWithBackSlashLocal(String str)
         {
             return replaceLocal(str, "\\", "/");
        }
        
 private String replaceLocal(String str, String original, String replacement)
	{
	    StringBuffer sb = new StringBuffer(str);
	    for (int i=0; i<sb.length(); i++)
	    {
		if (sb.substring(i,i+1).equals(original))
		    sb.replace(i,i+1,replacement);
	    }
	    return sb.toString();
}

private
	    DocRepository  
	    getDocRepositoryLocal(WFSession wfSession,String password)
	        throws Exception
	    {
	        DMS dms =  WFObjectFactory.getDMS(wfSession, wfSession.getUserName(), password);
	        return WFObjectFactory.getDocRepository(dms);
	    }
    public void debugLcl (boolean trace, Writer out, String msg) throws Exception
	{
	    if (trace) {
		System.out.println(msg);
	    }
    }
    private void createDocumentLocal(DocRepository docRepository,String clientPath,String fileName)throws Exception
        {
        try{
            File inFile= docRepository.checkOut(fileName,false);
    
    
                List tempDecisionTables = new ArrayList();
                FileInputStream fstream = new FileInputStream(inFile);
                OutputStream  fout= new FileOutputStream(clientPath);
                ObjectInputStream istream = new ObjectInputStream(fstream);
                Object obj = istream.readObject();
                tempDecisionTables = (ArrayList) obj;
                ByteArrayOutputStream bos = new ByteArrayOutputStream();
                ObjectOutputStream oos = new ObjectOutputStream( bos);
                oos.writeObject(tempDecisionTables);
                oos.flush();
                byte buffer [] = bos.toByteArray();
                fout.write(buffer);
    
                istream.close();
                fstream.close();
                fout.close();
                bos.close();
                oos.close();
                }
                catch(Exception e){
                	throw e;
                    }
    }
    
    public
        long
        getProcessDefinitionLatestIdLocal(
            WFSession wfSession,String planName)
            throws Exception
        {
    	long pdId = -1;
            WFObjectList wfObjectList = null;
            wfObjectList = WFObjectFactory.getWFObjectList(wfSession);
            wfObjectList.openList(Filter.AllPlans);
            Object[] pList = wfObjectList.getAllObjects();
            wfObjectList.closeList();
             if ( pList != null && pList.length != 0 ) {
                for (int pListIndex = 0; pListIndex < pList.length; pListIndex++)
                {
                   Plan plan =  (Plan)pList[pListIndex];
    			   if(plan.getName().equals(planName)){
    			    pdId=plan.getId();
    			   }
                }
            }
            return pdId;
    }
 %>
