<%@page contentType="text/html;charset=UTF-8" pageEncoding="ISO-8859-1" session="true"
%><%@page errorPage="Exception.jsp"
%><%@page import="com.fujitsu.iflow.common.JSConversions"
%><%@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.Arrow"
%><%@page import="com.fujitsu.iflow.model.workflow.BranchSpec"
%><%@page import="com.fujitsu.iflow.model.workflow.ConditionSpec"
%><%@page import="com.fujitsu.iflow.model.workflow.DataItemRef"
%><%@page import="com.fujitsu.iflow.model.workflow.Filter"
%><%@page import="com.fujitsu.iflow.model.workflow.FormRef"
%><%@page import="com.fujitsu.iflow.model.workflow.JavaAction"
%><%@page import="com.fujitsu.iflow.model.workflow.JavaActionSet"
%><%@page import="com.fujitsu.iflow.model.workflow.Node"
%><%@page import="com.fujitsu.iflow.model.workflow.Plan"
%><%@page import="com.fujitsu.iflow.model.workflow.TimerAction"
%><%@page import="com.fujitsu.iflow.model.workflow.TimerDef"
%><%@page import="com.fujitsu.iflow.model.workflow.TriggerDef"
%><%@page import="java.awt.Point"
%><%@page import="java.io.Writer"
%><%@page import="java.util.Arrays"
%><%@page import="java.util.Enumeration"
%><%@page import="java.util.Hashtable"
%><%
    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;
    }


    selectedPlanID = (String)request.getParameter("planID");
    if (selectedPlanID == null) {
        // Try with 'planId' - becoz when request comes from XPDLGenerator.
        selectedPlanID = (String)request.getParameter("planId");
        if (selectedPlanID == null)
            throw new Exception("ProcessDefintion.jsp requires the plan id to be specified as a 'planID' paramater.  No such parameter was found on this invocation.");
    }

    Plan selPlan = bps.getPlan(Integer.parseInt(selectedPlanID));
    String desc = selPlan.getDesc();
    showEditButtons = selPlan.isInEditMode();
    session.setAttribute("TabIndex","2");
//set URL
    StringBuffer reqURL = request.getRequestURL();
    reqURL.append("?");
    if (request.getQueryString() != null) {
        reqURL.append(request.getQueryString());
    }
    session.setAttribute("referralURL", reqURL.toString());


%>
<HTML>
<HEAD>
<title>Interstage Business Process Manager | Process Definition</TITLE>
<jsp:include page="StyleSheet.jsp" flush="true"/>
<script language="javascript" src="styles/clockscripts.js"></script>
<style>
.divdhtmlcontent{display:none;}
.divdhtmlcontentshow{display:show;}
</style>
</HEAD>
<body class="bodyClass" onLoad="goforit();">
<jsp:include page="Header.jsp" flush="true"/>


<br><pre>
    Plan plan = WFObjectFactory.getPlan();  //create new plan
    plan.setWFSession(wfSession);
    plan.startEdit();                       //start editing
<%
    writeSetter(out, "plan.setName", selPlan.getName());
    writeSetter(out, "plan.setTitle", selPlan.getTitle());
    writeSetter(out, "plan.setDesc", selPlan.getDesc());
    writeSetter(out, "plan.setOwner", selPlan.getOwner());
    writeSetter(out, "plan.setProcOwnerRoleScript", selPlan.getProcOwnerRoleScript());
    writeSetter(out, "plan.setInitScript", selPlan.getInitScript());
    writeSetter(out, "plan.setCommitScript", selPlan.getCommitScript());

%>
<%
    DataItemRef[] dirz = selPlan.getDataItemRefs();
    int last = dirz.length;
    for (int i=0; i<last; i++)
    {
        DataItemRef dif = dirz[i];
        writeSetter2(out, "plan.addDataItemRef", dif.getName(), dif.getType());
    }

    Node[] allNodes = selPlan.getNodes();

    NodeComparator nc = new NodeComparator();
    Arrays.sort(allNodes, nc);

    last = allNodes.length;
    for (int i=0; i<last; i++)
    {
        Node n = allNodes[i];
        String nodeName = "node"+n.getNodeId();
        out.write("\n    Node "+nodeName+" = plan.addNode(");
        writeLiteral(out,n.getName());
        out.write(",");
        out.write(Long.toString(n.getType()));
        out.write(");\n");
        if (n.supportRole()) {
            writeSetter(out, nodeName+".setRole", n.getRole());
        }
        writeSetter(out, nodeName+".setDesc", n.getDesc());
        if (n.supportPrologueScript()) {
            writeSetter(out, nodeName+".setPrologueScript", n.getPrologueScript());
        }
        if (n.supportEpilogueScript()) {
            writeSetter(out, nodeName+".setEpilogueScript", n.getEpilogueScript());
        }
    }

%>
<%
    Arrow[] allArrows = selPlan.getArrows();
    last = allArrows.length;
    for (int i=0; i<last; i++)
    {
        Arrow a = allArrows[i];
        out.write("    plan.addArrow(");
        writeLiteral(out,a.getName());
        out.write(", ");
        out.write(Integer.toString(a.getType()));
        out.write(", node");
        out.write(Long.toString(a.getSourceNode().getNodeId()));
        out.write(", node");
        out.write(Long.toString(a.getTargetNode().getNodeId()));
        out.write(");\n");
    }

%>
    plan = plan.createProcessDef();  //commit the new plan
</pre>


</body>
</html>

<%!

    boolean showEditButtons =false;
    String  selectedPlanID = null;

    final int AS_SCRIPT = 1;
    final int AS_TEXT = 2;
    final int AS_HEADER = 3;
    final int AS_HTML = 4;


    public
    void
    writeAll(Writer out, int level, String name, String value, int format, String loc)
         throws Exception
    {
        //suppress null values when not editing
        if (!showEditButtons) {
            if (value==null) {
                return;
            }
            if (value.length()==0) {
                return;
            }
        }
        out.write("<tr>");
        int leftOver = 740;
        if (showEditButtons) {
            leftOver -= 10;
        }
        if (level > 1) {
            out.write("<td class=\"evenrow\" width=\"50\"></td>");
            leftOver -= 50;
            if (level > 2) {
                out.write("<td class=\"evenrow\" width=\"50\"></td>");
                leftOver -= 50;
            }
        }
        out.write("<td class=\"oddrow\" width=\"50\"><font face=verdana size=1>");
        out.write(name);
        out.write("</font></td>\n    <td  class=\"TxtField\" colspan=\"");
        out.write(Integer.toString(4-level));
        out.write("\" width=\"");
        out.write(Integer.toString(leftOver));
        out.write("\"><font face=verdana size=1>");
        if (value == null)
        {
            out.write("<i>null</i>");
        }
        else if (format == AS_SCRIPT)
        {
            out.write("</font>");
            writeScript(out, value);
            out.write("<font face=verdana size=1>");
        }
        else if (format == AS_TEXT)
        {
            QuickForm.writeHtmlWithLineBreaks(out, value);
        }
        else if (format == AS_HEADER)
        {
            out.write("<b>");
            QuickForm.writeHtmlWithLineBreaks(out, value);
            out.write("</b>");
        }
        else if (format == AS_HTML)
        {
            out.write(value);
        }
        else
        {
            QuickForm.writeHtmlWithLineBreaks(out, "unknown format");
        }
        out.write("</font>");
        if (showEditButtons)
        {
            out.write("</td><td width=\"10\" bgcolor=\"#FFFFFF\">");
            if (loc!=null) {
                out.write("<a href=\"EditPD.jsp?pdId=");
                out.write(selectedPlanID);
                out.write("&mode=");
                out.write(loc);
                out.write("\"><img border=\"0\" src=\"images/edit_sm.gif\"></a>");
            }
        }
        out.write("</td></tr>\n");
        out.flush();
    }

    public
    void
    writeLink1(Writer out, String name, String value)
         throws Exception
    {
        out.write("<tr><td class=\"oddrow\" width=\"50\"><font face=verdana size=1>");
        out.write(name);
        out.write("</td>\n    <td  class=\"TxtField\" colspan=\"3\"><font face=verdana size=1>");
        if (value == null) {
            out.write("<i>null</i>");
        }
        else {
            out.write("<a href=\"");
            QuickForm.writeHtml(out, value);
            out.write("\">");
            QuickForm.writeHtml(out, value);
            out.write("</a>");
        }
        out.write("</font></td></tr>\n");
        out.flush();
    }

    public
    void
    writeAction1(Writer out, String name, JavaActionSet jas)
        throws Exception
    {
        if (jas == null) {
            writeAll(out, 1, name, null, AS_TEXT, null);
            return;
        }
        JavaAction[] jaa = jas.getJavaActions();
        if (jaa == null) {
            writeAll(out, 1, name, null, AS_TEXT, null);
            return;
        }
        int count = jas.getActionCount();
        for (int i=0; i<count; i++) {
            JavaAction ja = jaa[i];

            out.write("<tr><td class=\"oddrow\" width=\"50\">");
            out.write(name);
            out.write("</td>\n    <td  class=\"TxtField\" colspan=\"3\" width=\"");
            if (showEditButtons) {
                out.write("740");
            }
            else {
                out.write("750");
            }
            out.write("\"><b>Name:</b>");
            QuickForm.writeHtml(out, ja.getActionName());
            out.write("<br>\n<b>Description:</b> ");
            QuickForm.writeHtml(out, ja.getActionDescription());
            out.write("<br>\n<b>Path:</b> ");
            QuickForm.writeHtml(out, ja.getClassPath());
            out.write("<br>\n<b>Class:</b> ");
            QuickForm.writeHtml(out, ja.getClassName());
            out.write("<br>\n<b>Method:</b> ");
            QuickForm.writeHtml(out, ja.getMethodName());
            out.write("<br>\n<b>Return:</b> ");
            QuickForm.writeHtml(out, ja.getReturnValueUDAName());
            out.write("<br>\n<b>Params:</b> ");
            QuickForm.writeHtml(out, ja.getArgumentsUDANames());
            out.write("<br>\n<b>Name:</b> ");
            QuickForm.writeHtml(out, ja.getActionName());
            out.write("<br>\n<b>Bean:</b> ");
            QuickForm.writeHtml(out, ja.getBeanName());
            out.write("<br>\n<b>B-Method:</b> ");
            QuickForm.writeHtml(out, ja.getBeanName());
            out.write("<br>\n<b>B-Args:</b> ");
            QuickForm.writeHtml(out, ja.getBeanMethodArgumentsUDANames());
            if (showEditButtons) {
                out.write("</td><td width=\"10\" bgcolor=\"#FFFFFF\">");
            }
            out.write("</td></tr>\n");
        }
        out.flush();
    }

    public
    void
    writeHeader2(Writer out, String name, String value)
        throws Exception
    {
        writeAll(out, 2, name, value, AS_HEADER, null);
    }

    public
    void
    writeSub2(Writer out, String name, long id, String value)
        throws Exception
    {
        out.write("<tr><td class=\"evenrow\" width=\"50\"></td><td class=\"oddrow\">");
        out.write(name);
        out.write("</td>\n    <td  class=\"TxtField\" colspan=\"2\"><a href=\"ProcessDefinition.jsp?planID=");
        out.write(Long.toString(id));
        out.write("\">");
        out.write(Long.toString(id));
        out.write(": ");
        if (value == null) {
            out.write("<i>null</i>");
        }
        else {
            QuickForm.writeHtml(out, value);
        }
        out.write("</a></td></tr>\n");
        out.flush();
    }

   public
    String
    printDate(long dateLong)
    {
        // TODO put the proper conversion to a date display format.
        if(dateLong==-1) return "";
        return  "<script> showDate('"+dateLong+"'); </script>";
    }


    /***************8
     * the only issue with printing scripts is that if you use the (pre) tag, and
     * if the script is very very long, it warps the whole table.  So this continues
     * to use the (pre) tag, but arbitrarily truncates the scripts if the line gets
     * longer than 80 characters.
     */
    public
    void
    writeScript(Writer out, String script)
        throws Exception
    {
        out.write("<tt>");
        int last = script.length();
        int start = 0;
        boolean beginningOfLine = true;
        for (int pos=0; pos < last; pos++) {
            char c = script.charAt(pos);

            // handle the indent spaces
            if (beginningOfLine) {
                if (c == ' ' || c=='\t') {
                    out.write("&nbsp;");
                    continue;
                }
                beginningOfLine = false;
            }

            // look for and handle end of line
            if (c == '\n') {
                String line = script.substring(start, pos);
                QuickForm.writeHtml(out, line);
                out.write("<br>\n");
                start = pos+1;
                beginningOfLine = true;
                continue;
            }

            // handle case where line is too long
            if (pos - start > 80) {
                String line = script.substring(start, pos);
                QuickForm.writeHtml(out, line);
                out.write("<br>\n");
                start = pos;
                continue;
            }
        }

        //remainder of script
        String line = script.substring(start, last);
        QuickForm.writeHtml(out, line);
        out.write("</tt>");
    }

    private
    void
    writeTrigger(Writer out, String label, TriggerDef trig)
        throws Exception
    {
        StringBuffer sit = new StringBuffer();
        sit.append("id: ");
        sit.append(Long.toString(trig.getId()));
        sit.append("\ntype: ");
        sit.append(Integer.toString(trig.getType()));
        sit.append("\nstate: ");
        sit.append(Integer.toString(trig.getState()));
        if (trig.isActive()) {
            sit.append("\nactive: true");
        }
        else {
            sit.append("\nactive: false");
        }
        sit.append("\nname: ");
        sit.append(trig.getName());
        sit.append("\ndescription:");
        sit.append(trig.getDescription());
        String[] conds = trig.getControlConditions();
        for (int i=0; i<conds.length; i++) {
            sit.append("\ncontrolCondition:");
            sit.append(conds[i]);
        }
        writeAll(out, 1, label, sit.toString(), AS_TEXT, null);
        int ac = trig.getActionCount();
        for (int actNo=0; actNo<ac; actNo++) {
            String[] param = trig.getActionParams(actNo);
            for (int i=0; i<param.length; i++) {
                writeAll(out, 2, "Params "+actNo+" "+i, param[i], AS_TEXT, null);
            }
            writeAll(out, 2, "Condition"+actNo, trig.getActionCondition(actNo), AS_TEXT, null);
        }

        Hashtable dMap = trig.getDataMap();
        Enumeration e1 = dMap.keys();
        while (e1.hasMoreElements()) {
            String key1 = (String) e1.nextElement();
            String value1 = (String) dMap.get(key1);
            writeAll(out, 2, "Data", key1 + " = " + value1, AS_TEXT, null);
        }
        Hashtable cMap = trig.getCorrelationMap();
        Enumeration e2 = cMap.keys();
        while (e2.hasMoreElements()) {
            String key2 = (String) e2.nextElement();
            String value2 = (String) dMap.get(key2);
            writeAll(out, 2, "Corr", key2 + " == " + value2, AS_TEXT, null);
        }
    }


    /**
    *   This comparator is used to sort the template list into ascending order
    *   relatively to their ID.
    */
    class PlanIDComparator implements java.util.Comparator
    {
        public int compare(Object obj1, Object obj2)
        {
            if ( obj1 == null || obj2 == null ||
                !(obj1 instanceof Plan) || !(obj2 instanceof Plan) )
                return 0;
            Plan plan1 = (Plan)obj1;
            Plan plan2 = (Plan)obj2;
            if ( plan1.getId() < plan2.getId() ) return -1;
            else return 1;
        }
    }

    // This comparitor is used to sort the activities into a reasonable
    // order.  It figures out how many hops the node is away from the
    // start node.  Then for all the nodes in the same number of
    // hops, it takes into account X & Y locations, closer to upper
    // left corner the earlier it will be in the list.

    class NodeComparator implements java.util.Comparator
    {
        NodeComparator() {}

        Hashtable jumpsFromStart = new Hashtable();

        public int compare(Object a, Object b) {
            Node nia = (Node) a;
            Node nib = (Node) b;
            Point pa = nia.getPosition();
            int vala = pa.x + 2*pa.y + 10000*findJumpsFromStart(nia);
            Point pb = nib.getPosition();
            int valb = pb.x + 2*pb.y + 10000*findJumpsFromStart(nib);
            if (vala < valb) {
                return -1;
            }
            if (vala == valb) {
                return 0;
            }
            return 1;
        }

        int findJumpsFromStart(Node ni) {
            // first check to see if we already knew the result
            Long id = new Long(ni.getNodeId());
            Integer storedVal = (Integer) jumpsFromStart.get(id);
            if (storedVal != null) {
                return storedVal.intValue();
            }

            // check to see if this is the start node
            int nodeType = ni.getType();
            if (nodeType == Node.TYPE_START) {
                jumpsFromStart.put(id, new Integer(0));
                return 0;
            }

            // prevent infinite loops
            jumpsFromStart.put(id, new Integer(-1));

            // now start search
            Arrow ai[] = ni.getIncomingArrows();
            int last = ai.length;
            for (int j=0; j<last; j++) {
                Arrow aij = ai[j];
                Node ni2 = aij.getSourceNode();
                int t = findJumpsFromStart(ni2);
                if (t >= 0) {
                    jumpsFromStart.put(id, new Integer(t+1));
                    return t+1;
                }
            }

            // if we get here, then a full depth search has not found
            // a start node, which means we are disconnected from
            // the start node, so return a high number
            jumpsFromStart.put(id, new Integer(100));
            return 100;
        }
    }


    void
    writeSetter(Writer out, String opName, String value)
        throws Exception
    {
        if (value == null || value.length() == 0) {
            return;  //don't write anything in null case
        }
        out.write("    ");
        out.write(opName);
        out.write("(");
        QuickForm.writeHtml(out, JSConversions.quote4JS(value));
        out.write(");\n");
    }

    void
    writeSetter2(Writer out, String opName, String val1, String val2)
        throws Exception
    {
        if (val1 == null || val1.length() == 0) {
            return;  //don't write anything in null case
        }
        out.write("    ");
        out.write(opName);
        out.write("(");
        QuickForm.writeHtml(out, JSConversions.quote4JS(val1));
        out.write(",");
        QuickForm.writeHtml(out, JSConversions.quote4JS(val2));
        out.write(");\n");
    }

    void
    writeLiteral(Writer out, String value)
        throws Exception
    {
        QuickForm.writeHtml(out, JSConversions.quote4JS(value));
    }

%>
