package org.jboss.console.plugins.monitor;

import org.jboss.monitor.ThresholdMonitor;
import org.jboss.mx.util.MBeanServerLocator;
import org.jfree.data.XYSeries;
import org.jfree.data.DefaultTableXYDataset;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartUtilities;
import org.jfree.chart.plot.PlotOrientation;

import javax.management.MBeanServer;
import javax.management.MalformedObjectNameException;
import javax.management.ObjectName;
import javax.management.Attribute;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.OutputStream;
import java.util.ArrayList;

/**
 * Created by IntelliJ IDEA.
 * User: wburke
 * Date: Nov 25, 2003
 * Time: 5:53:01 PM
 * To change this template use Options | File Templates.
 */
public class ManageSnapshotServlet extends javax.servlet.http.HttpServlet
{
   protected void doGet(HttpServletRequest req, HttpServletResponse resp)
           throws ServletException, IOException
   {
      doit(req, resp);
   }

   protected void doPost(HttpServletRequest req, HttpServletResponse resp)
           throws ServletException, IOException
   {
      doit(req, resp);
   }

   protected void error(String msg, HttpServletRequest req, HttpServletResponse resp)
           throws ServletException, IOException
   {
      req.setAttribute("error", "Error: " + msg);
      //this.getServletContext().getRequestDispatcher("/createThresholdMonitor.jsp").forward(req, resp);
      req.getRequestDispatcher("/manageSnapshot.jsp").forward(req, resp);
      return;
   }

   protected void doit(HttpServletRequest req, HttpServletResponse resp)
           throws ServletException, IOException
   {
      String action = req.getParameter("action");
      if (action == null)
      {
         error("unknown action: ", req, resp);
         return;
      }
      action = action.trim();
      String monitorName = req.getParameter("monitorName").trim();
      MBeanServer mbeanServer = MBeanServerLocator.locateJBoss();
      ObjectName monitorObjectName, oname = null;
      String attribute = null;
      try
      {
         monitorObjectName = new ObjectName(req.getParameter("monitorObjectName"));
         attribute = (String)mbeanServer.getAttribute(monitorObjectName, "ObservedAttribute");
      }
      catch (Exception ex)
      {
         error("Malformed Monitor ObjectName: " + req.getParameter("monitorObjectName"), req, resp);
         return;
      }
      if (action.equals("Start Snapshot"))
      {
         Object[] nullArgs = {};
         String[] nullSig = {};
         try
         {
            mbeanServer.invoke(monitorObjectName, "startSnapshot", nullArgs, nullSig);
         }
         catch (Exception ex)
         {
            error("Problem invoking startSnapshot: " + ex.toString(), req, resp);
            return;
         }
         req.getRequestDispatcher("/manageSnapshot.jsp").forward(req, resp);
         return;
      }
      else if (action.equals("Stop Snapshot"))
      {
         Object[] nullArgs = {};
         String[] nullSig = {};
         try
         {
            mbeanServer.invoke(monitorObjectName, "endSnapshot", nullArgs, nullSig);
         }
         catch (Exception ex)
         {
            error("Problem invoking endSnapshot: " + ex.toString(), req, resp);
            return;
         }
         req.getRequestDispatcher("/manageSnapshot.jsp").forward(req, resp);
         return;
      }
      else if (action.equals("Clear Dataset"))
      {
         Object[] nullArgs = {};
         String[] nullSig = {};
         try
         {
            mbeanServer.invoke(monitorObjectName, "clearData", nullArgs, nullSig);
         }
         catch (Exception ex)
         {
            error("Problem invoking clearData: " + ex.toString(), req, resp);
            return;
         }
         req.setAttribute("error", "Dataset Cleared!");
         req.getRequestDispatcher("/manageSnapshot.jsp").forward(req, resp);
         return;
      }
      else if (action.equals("Remove Snapshot"))
      {
         try
         {
            System.out.println("removing snapshot: " + monitorObjectName.toString());
            mbeanServer.unregisterMBean(monitorObjectName);
            req.getRequestDispatcher("/ServerInfo.jsp").forward(req, resp);
         }
         catch (Exception ex)
         {
            error("Failed to Remove Monitor: " + ex.toString(), req, resp);
         }
         return;
      }
      else if (action.equals("Show Dataset"))
      {
         ArrayList data = null;
         long start, end = 0;
         try
         {
            data = (ArrayList)mbeanServer.getAttribute(monitorObjectName, "Data");
            start = ((Long)mbeanServer.getAttribute(monitorObjectName, "StartTime")).longValue();
            end = ((Long)mbeanServer.getAttribute(monitorObjectName, "EndTime")).longValue();
         }
         catch (Exception ex)
         {
            error("Problem invoking getData: " + ex.toString(), req, resp);
            return;
         }
         resp.setContentType("text/html");
         PrintWriter writer = resp.getWriter();
         writer.println("<html>");
         writer.println("<body>");
         writer.println("<b>Start Time:</b> " + start + "ms<br>");
         writer.println("<b>End Time:</b> " + end + "ms<br>");
         writer.println("<b>Total Time:</b> " + (end - start) + "ms<br>");
         writer.println("<br><table border=\"0\">");
         for (int i = 0; i < data.size(); i++)
         {
            writer.println("<tr><td>" + data.get(i) + "</td></tr");
         }
         writer.println("</table></body></html>");
         return;
      }
      else if (action.equals("Graph Dataset"))
      {
         ArrayList data = null;
         long start, end = 0;
         try
         {
            data = (ArrayList)mbeanServer.getAttribute(monitorObjectName, "Data");
            start = ((Long)mbeanServer.getAttribute(monitorObjectName, "StartTime")).longValue();
            end = ((Long)mbeanServer.getAttribute(monitorObjectName, "EndTime")).longValue();
         }
         catch (Exception ex)
         {
            error("Problem invoking getData: " + ex.toString(), req, resp);
            return;
         }
         XYSeries set = new XYSeries(attribute, false);
         for (int i = 0; i < data.size(); i++)
         {
            set.add(new Integer(i), (Number)data.get(i));
         }
         DefaultTableXYDataset dataset = new DefaultTableXYDataset(set);
         JFreeChart chart = ChartFactory.createXYLineChart(
                 "JMX Attribute: " + attribute, "count", attribute, dataset,
                 PlotOrientation.VERTICAL,
                 true,
                 true,
                 false
         );
         resp.setContentType("image/png");
         OutputStream out = resp.getOutputStream();
         ChartUtilities.writeChartAsPNG(out, chart, 400, 300);
         out.close();
         return;
      }
      error("Unknown Action", req, resp);
      return;
   }

}
