/*
 * ServletEntity.java
 *
 * Created on October 18, 2000, 12:05 PM
 */

package ovt.servlet;

import ovt.*;
import ovt.gui.*;
import ovt.mag.*;
import ovt.util.*;
import ovt.event.*;
import ovt.object.*;
import ovt.graphics.*;
import ovt.datatype.*;
import ovt.offscreen.*;
import ovt.interfaces.*;

import java.io.*;
import java.util.*;
import java.beans.*;
import java.awt.*;
import java.awt.image.*;

import javax.servlet.*;
import javax.servlet.jsp.*;
import javax.servlet.http.*;


/**
 *
 * @author  ko
 * @version 
 */
public class ServletEntity implements HttpSessionBindingListener {
  static Object lock = new Object();
  static int numberOfEntities = 0;  
  OVTCore core;
  OffscreenRenPanel renPanel;
  //HtmlTreePanel treePanel;
  
  //OVTServlet servlet;

  /** Creates new ServletEntity */
  public ServletEntity() {
    //this.servlet = servlet;
    renPanel = new OffscreenRenPanel();
    renPanel.setSize(400, 400);
    Log.log("Offscreen Panel created.\n", 5);
    /*String ovt_home = System.getenv("OVT_HOME");
    String ovt_user_dir = System.getenv("OVT_USER_DIR");
    System.setProperty("ovt.home", ovt_home);
    System.setProperty("ovt.user", ovt_user_dir);*/
    synchronized(lock) {
        core = new OVTCore(renPanel.getRenderer(), renPanel);
    }
    
    float[] rgb = core.getBackgroundColor().getRGBColorComponents(null);
    renPanel.getRenderer().SetBackground(rgb[0], rgb[1], rgb[2]);
    
    Time time = new Time(new GregorianCalendar(TimeZone.getTimeZone("GMT00")));    
    double startMjd = time.getMjd() - 5*1./24.;
    double intervalMjd  = 2*5*1./24.;
    double stepMjd  = 1./24./2.;  // 30 min
    
    TimeSet ts = new TimeSet(startMjd, intervalMjd, stepMjd);
    double currentMjd = ts.getClosestFor(time.getMjd());
    //ts.setCurrentMjd(time.getMjd());
    try { 
        core.getTimeSettings().setTime(ts); 
        core.getTimeSettings().setCurrentMjd(currentMjd); 
    } catch (PropertyVetoException e2) { e2.printStackTrace(); }
    
    try {
        core.setAsText(new PropertyPath("OVT.Satellites.Cluster.Cluster1.Sat.visible"), "show");
        core.setAsText(new PropertyPath("OVT.Satellites.Cluster.Cluster1.Orbit.visible"), "show");
        core.setAsText(new PropertyPath("OVT.Magnetopause.visible"), "show");
        //core.setAsText(new PropertyPath("OVT.Camera.viewTo"), "Cluster1");
        core.getCamera().setViewFrom(Camera.VIEW_FROM_Y);
        core.getCamera().setR(60);
        //core.getCamera().reset();
    } catch (PropertyVetoException e2) {  e2.printStackTrace(); }
    //core.setAsText("OVT.Satellites.Cluster.Cluster1.FieldLines.visible", "true");
    Log.log("OVTServlet :: init done.", 5);
  }


public OVTCore getCore() {
    return core;
}

public OffscreenRenPanel getRenPanel() {
    return renPanel;
}

public void process(HttpServletRequest req, HttpServletResponse res, ServletContext context)
        throws IOException, ServletException, JspException {
    
    Log.log("Processing parameters... ", 5);
    
    Enumeration e = req.getParameterNames();
    String paramName;
    while(e.hasMoreElements()) {
        paramName = (String)e.nextElement();
        if (!paramName.equals("get") && !paramName.equals("obj")) {
            try {
                core.setAsText(new PropertyPath(paramName), req.getParameter(paramName));
            } catch (PropertyVetoException e2) {
                Log.log("Error: " + e2.getMessage(), 0);
                throw new JspException(e2.getMessage());
            } catch (IllegalArgumentException ignore) {
                Log.log("Ignoring : " + ignore.getMessage(), 6);
            } 
        }
    }
    
}


void sendRenPanelImage(HttpServletResponse res) {
    Log.log("Sending RenPanel Image ...", 5);
    try {
    res.setContentType("image/jpeg");
    
        ServletOutputStream out = res.getOutputStream();
        Log.log("Getitng image ..", 5);
        Image img = renPanel.getImage();
        Log.log("image created. creating encoder ...", 5);
        JpegEncoder enc = new JpegEncoder(img, 90, out); 
        Log.log("encoder created", 5);
        enc.Compress();
        Log.log("Compressed", 5);
        //GifEncoder enc = new GifEncoder(renPanel.getImage(), out); 
        //enc.encode();
    } catch (IOException e) {
        e.printStackTrace(); 
        Log.log("IOException : " + e);
    }
}

 void sendLargeImage(HttpServletResponse res, int magnification) throws IllegalArgumentException {
    if (magnification > 5) throw new IllegalArgumentException("Magnification > 5 is prohibited!");
    Log.log("Sending Large Image ...", 5);
    try {
        res.setContentType("image/jpeg");
    
        ServletOutputStream out = res.getOutputStream();
        Log.log("Getitng image ..", 5);
        LargeImage li = new LargeImage(renPanel.getRenderer());
        li.setMagnification(magnification);
        Image img = li.getImage(renPanel.getLock());
        //Log.log("image created. creating encoder ...", 5);
        JpegEncoder enc = new JpegEncoder(img, 90, out); 
        //Log.log("encoder created", 5);
        enc.Compress();
        //Log.log("Compressed", 5);
        //GifEncoder enc = new GifEncoder(renPanel.getImage(), out); 
        //enc.encode();
    } catch (IOException e) {
        e.printStackTrace(); 
        Log.log("IOException : " + e);
    }
}


public static void gotoJSPErrorPage(HttpServletRequest req, HttpServletResponse res,
            ServletContext context, String errorPageUrlString, Throwable throwable) 
            throws ServletException, IOException {
   req.setAttribute("javax.servlet.jsp.jspException", throwable);
   context.getRequestDispatcher(errorPageUrlString).forward(req, res);
}

public static String getCB() {
    return "/servlet/ovt";
}

public static String getImagesDir() {
    return "/img/";
}

  
public static synchronized void changeNumberOfEntities(int inc) {
    if (inc > 0) numberOfEntities++;
    else numberOfEntities--;
}

public static int getNumberOfEntities() {
    return numberOfEntities;
}

public static int getMaxNumberOfEntities() {
    return 5;
}

/** This method is executed when session expires */
public void valueUnbound(HttpSessionBindingEvent evt) {
    Log.log("Session expired!!!");
    changeNumberOfEntities(-1);
}

/** This method is executed when servlet entity is being added to session */
public void valueBound(HttpSessionBindingEvent evt) {
    Log.log("Session created!!!");
    changeNumberOfEntities(+1);
}

}