package org.projectapollo.demo.Jobs.StatusBar;

import apollo.*;
import apollo.Template.*;
import apollo.Storable.*;
import apollo.Job.*;

import org.projectapollo.demo.Storable.*;

import java.util.*;
import java.text.*;

import apollo.Session.*;

public class StatusBarBroker extends PageBroker {

    Vector AS;
    AcceptClause normalEntry;
    AcceptClause clearJob;
    AcceptClause showSpecificJob;
    AcceptClause showSpecificJobForeground;

    public StatusBarBroker(ManagerTracker MT,String fquid,PageBroker PB) throws TemplatePageException {
        super(MT,fquid,PB);
 
        MT.getPM().registerTemplatePage(FQUID,
new TemplatePage(MT,this, false));
        MT.getPM().registerTemplatePage(FQUID+
".Blank", new TemplatePage(MT, this, "blank.html"));
        AS =
new Vector();

        normalEntry=
new AcceptClause("NormalEntry");
        clearJob =
new AcceptClause("ClearJob");
        showSpecificJob =
new AcceptClause("ShowSpecificJob");

        showSpecificJobForeground =
new AcceptClause("ShowSpecificJobForeground");
        showSpecificJob.addAcceptClause(AcceptClause.INT,
"JobID", AcceptClause.REQUIRED);
        showSpecificJobForeground.addAcceptClause(AcceptClause.INT,
"JobID", AcceptClause.REQUIRED);
        showSpecificJobForeground.addAcceptClause(AcceptClause.STRING,
"Foreground", AcceptClause.REQUIRED);

        clearJob.addAcceptClause(AcceptClause.STRING,
"Clear", AcceptClause.REQUIRED);

        AS.addElement(showSpecificJobForeground);
        AS.addElement(showSpecificJob);
        AS.addElement(clearJob);
        AS.addElement(normalEntry);
}
 
    public HTTPResponse getJobDisplay(Job job, EntryAssertionManager EAM, TransactionTracker TT, WebSession thisSession) throws ApolloException {
        Hashtable RT =
new Hashtable();
        RT.put(
"JobID", new Integer(job.getJobID()));
        RT.put(
"Finished", new Boolean(job.getStatusID()==JobManager.JOB_FINISHED));
        RT.put(
"Failed", new Boolean(job.getStatusID()==JobManager.JOB_FAILED));
        RT.put(
"ShowPercentageBar", new Boolean(true));
        if (EAM.isAccept(showSpecificJobForeground)) {
            RT.put(
"Foreground", new Boolean(true));
        }
else {
            RT.put(
"Foreground", new Boolean(false));
        }
        if (job.getStatusID()==JobManager.JOB_RUNNING) {
            RT.put(
"Status", "Running");
            RT.put(
"Refresh", new Boolean(true));
        }
       
if (job.getStatusID()==JobManager.JOB_UNINITIALIZED) {
            RT.put(
"Status", "Initializing");
            RT.put(
"Refresh", new Boolean(true));
            RT.put(
"ShowPercentageBar", new Boolean(false));
        }
else if (job.getStatusID()==JobManager.JOB_FAILED) {
            RT.put(
"Status", "Failed");
            RT.put(
"FailedLink", new Boolean(true));
            RT.put(
"Refresh", new Boolean(false));
            if (!EAM.isAccept(showSpecificJobForeground)) {
                RT.put(
"ClearButton", new Boolean(true));
            }
        }
else if (job.getStatusID()==JobManager.JOB_FINISHED) {
            RT.put(
"Status", "Finished");
            if (!(job.getJobResult().getResultTypeID()==JobMembership.RETURN_TYPE_NONE)) {
                RT.put(
"ResultsLink", new Boolean(true));
            }
 
 
            if (job.getJobResult().getResultTypeID()==JobMembership.RETURN_TYPE_FQUID) {
                if (EAM.isAccept(showSpecificJobForeground)) {
 
                     //Return type is a FQUID, send them there! (if this is in the main window)
                     HTTPRequest req = new HTTPRequest();
                    return
MT.getPM().handleRequest(TT, job.getJobResult().getResult(), req, thisSession);
                }
else {
                    RT.put(
"ResultsLink", new Boolean(false));
                }
            }

            RT.put(
"Refresh", new Boolean(false));
            if (!EAM.isAccept(showSpecificJobForeground)) {
                RT.put(
"ClearButton", new Boolean(true));
            }
        }
 
        RT.put(
"JobName", job.getJobName());
        NumberFormat nf = DecimalFormat.getPercentInstance();
        nf.setMaximumFractionDigits(
0);

       
if (job.getPercentage()==0) {
            RT.put(
"ShowPercentageBar", new Boolean(false));
        }
        RT.put(
"Percentage", nf.format(job.getPercentage()));

       
if (job.getPercentage()<1) {
            RT.put(
"NotFinished", new Boolean(true));
        }
else {
            RT.put(
"NotFinished", new Boolean(false));
        }

        if (job.getExtendedStatus()!=null) {
            RT.put(
"ShowExtendedStatus", new Boolean(true));
            RT.put(
"ExtendedStatus", job.getExtendedStatus());
        }
else {
            RT.put(
"ShowExtendedStatus", new Boolean(false));
        }
        return MT.getPM().getPage(FQUID).render(RT,thisSession);
    }
 
 
    public HTTPResponse getNoJobDisplay(ManagerTracker MT, WebSession thisSession) throws TemplatePageException {
        return MT.getPM().getPage(FQUID+".Blank").render(null, thisSession);
    }
 
 
    public HTTPResponse render(TransactionTracker TT, HTTPRequest req, WebSession thisSession) throws ApolloException {
        EntryAssertionManager EAM =
new EntryAssertionManager(MT, AS);
        EAM.evaluate(req);
 
        if (EAM.isAccept(clearJob)) {
            thisSession.setValue(
"MonitorJobID",null);
            return getNoJobDisplay(MT, thisSession);
        }
 
 
        int jobID;
        if (EAM.isAccept(showSpecificJob) || EAM.isAccept(showSpecificJobForeground)) {
            jobID=EAM.getInt(
"JobID");
        }
else {
            User u = (User) thisSession.getValue(
"User");
 
           
if (thisSession.getValue("MonitorJobID") == null) {
                // Check for running jobs for this user
 
                //Fetch running uncompleted jobs
                 WhereQuery wq = new WhereQuery();
                wq.insertWhereClause(WhereQuery.AND,
"userID", JobMembership.class, u.getUserID());
                wq.insertWhereClause(WhereQuery.AND,
"JobID", JobRecord.class, "JobID", JobMembership.class); //Join point
                 wq.insertWhereClause(WhereQuery.AND, "StatusID", JobRecord.class, new Integer(JobManager.JOB_FAILED), WhereQuery.NOT_EQUAL);
                wq.insertWhereClause(WhereQuery.AND,
"StatusID", JobRecord.class, new Integer(JobManager.JOB_FINISHED), WhereQuery.NOT_EQUAL);
                Vector j = JobRecord.loadVectorInstance(MT, wq);
                if (j.size()>0) {
                    JobRecord jr = (JobRecord) j.firstElement();
                    thisSession.setValue(
"MonitorJobID", new Integer(jr.getJobID()));
                    jobID=jr.getJobID();
                }
else {
                     //return blank page
                    return getNoJobDisplay(MT, thisSession);
                }
            }
else {
                jobID=((Integer)thisSession.getValue(
"MonitorJobID")).intValue();
            }
        }
        return getJobDisplay(MT.getJM().getJob(jobID), EAM, TT, thisSession);
    }
}