/*--
  This file is a part of ZetaGrid, a simple and secure Grid Computing
  kernel.

  Copyright (c) 2001-2004 Sebastian Wedeniwski.  All rights reserved.

  Use in source and binary forms, with or without modification,
  are permitted provided that the following conditions are met:

  1. The source code must retain the above copyright
     notice, this list of conditions and the following disclaimer.

  2. The origin of this software must not be misrepresented; you must 
     not claim that you wrote the original software.  If you plan to
     use this software in a product, please contact the author.

  3. Altered source versions must be plainly marked as such, and must
     not be misrepresented as being the original software. The author
     must be informed about these changes.

  4. The name of the author may not be used to endorse or promote 
     products derived from this software without specific prior written 
     permission.

  THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS
  OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
  DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
  GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
  INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
  WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
  NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

  Version 1.8.6, July 4, 2003

  This program is based on the work of:
     S. Wedeniwski
--*/

package zeta.handler.statistic;

import java.awt.Color;
import java.awt.Paint;
import java.awt.image.BufferedImage;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Types;
import java.text.DecimalFormat;

import javax.servlet.ServletException;

import zeta.ZetaServlet;
import zeta.util.Charts;
import zeta.util.QueryWithSum;
import zeta.util.Table;

/**
 *  Handles a GET request for the statistic 'operating systems'.
**/
public class OperatingSystemsHandler extends AbstractHandler {
  /**
   *  @param servlet  servlet which owns this handler.
  **/
  public OperatingSystemsHandler(ZetaServlet servlet) {
    super(servlet, 3600000, 3600000, 86400000);  // 60 min., 60 min., 24 h
  }

  /**
   *  Determines the width of the image in the statistic page.
   *  @param  imageName name of the image
   *  @return the width of the image in the statistic page.
  **/
  public int getImageWidth(String imageName) {
    return (imageName.equals("pie"))? imgWidthPie : imgWidth;
  }

  /**
   *  Determines the height of the image in the statistic page.
   *  @param  imageName name of the image
   *  @return the height of the image in the statistic page.
  **/
  public int getImageHeight(String imageName) {
    return (imageName.equals("pie"))? imgHeightPie : imgHeight;
  }

  /**
   *  Creates HTML page with the content of the statistic 'operating systems'.
   *  @param  con  connection to the back-end database
   *  @return HTML page with the content of the statistic 'operating systems'.
  **/
  public String createPage(Connection con) throws SQLException, ServletException {
    StringBuffer buffer = new StringBuffer(70*1024);
    /*buffer.append("<tr><td colspan=\"6\">");
    buffer.append("<p><center><img src=\"operatingsystems?image=histogram\"/ width=\"");
    buffer.append(imgWidth);
    buffer.append("\" height=\"");
    buffer.append(imgHeight);
    buffer.append("\"></center>");
    buffer.append("</td></tr>");*/
    buffer.append("<tr><td colspan=\"6\" height=\"30pt\" class=\"second-head-gray\"><center>Under which operating systems were the zeros verified:</center></td></tr>");
    buffer.append("<tr><td colspan=\"6\">");
    buffer.append("<br><center>");

    HtmlTableGenerator generator = new HtmlTableGeneratorWithSum(servlet);
    Table table = new QueryWithSum(null, "WITH a (server_id,workstation_id,os_name,os_arch,ws_zeros) AS"
                           + " (SELECT comp.server_id,comp.workstation_id,"
                           + "  ws.os_name,ws.os_arch,SUM(CAST(comp.range AS DECIMAL(15, 0))) AS ws_zeros"
                           + "   FROM zeta.computation comp, zeta.result res, zeta.workstation ws"
                           + "   WHERE res.task_id=comp.task_id"
                           + "   AND res.work_unit_id=comp.work_unit_id"
                           + "   AND comp.server_id=ws.server_id"
                           + "   AND comp.workstation_id=ws.id"
                           + "   AND ws.os_arch<>''"
                           + "   GROUP BY comp.server_id,comp.workstation_id,ws.os_name,ws.os_arch)"
                           + "SELECT os_name AS \"operating system\",os_arch AS \"processor\","
                           + "COUNT(*) AS \"computers\",SUM(ws_zeros) AS \"zeros\""
                           + " FROM a GROUP BY os_name,os_arch ORDER BY os_name,os_arch", con, servlet).getResult();
    //updatePie(table);
    extendPercent(table);
    buffer.append(generator.generate(table));
    /*buffer.append("<br>&nbsp;<p><img src=\"operatingsystems?image=pie\"/ width=\"");
    buffer.append(imgWidthPie);
    buffer.append("\" height=\"");
    buffer.append(imgHeightPie);
    buffer.append("\">");*/
    buffer.append("</center></td></tr>");
    return buffer.toString();
  }

  /**
   *  Creates PNG image for a specified name which is defined in the HTML page.
   *  @param  con  connection to the back-end database
   *  @param  imageName name of the image
   *  @return PNG image for a specified name which is defined in the HTML page.
  **/
  public BufferedImage createImage(Connection con, String imageName) throws SQLException, ServletException {
    if (imageName.equals("pie")) {
      if (names == null) {
        createPage(con);
        BufferedImage image = Charts.generatePie(getImageWidth(imageName), getImageHeight(imageName), names, values);
        names = null;
        return image;
      } else {
        return Charts.generatePie(getImageWidth(imageName), getImageHeight(imageName), names, values);
      }
    } else {
      final String[] verticalAxisLabels = { "Number of computers", "Number of new computers", "Number of active computers" };
      final Paint[] colors = { Color.blue, Color.red, Color.green };
      final int[] weight = { 5, 1, 1 };
      final int[][] combination = { {0}, {1}, {2} };
      return Charts.generateChart(getImageWidth(imageName), getImageHeight(imageName), "Number of computers", "Date", verticalAxisLabels, colors, weight, combination, Charts.createNumberOfComputers(con));
    }
  }

  private void extendPercent(Table table) {
    int l = table.getRowCount()-1;
    int columns = table.getColumnCount();
    long sum1 = 0;
    long sum2 = 0;
    for (int i = 0; i < l; ++i) {
      Number value = (Number)table.getValue(i, columns-2);
      if (value != null) {
        sum1 += value.intValue();
      }
      value = (Number)table.getValue(i, columns-1);
      if (value != null) {
        sum2 += value.longValue();
      }
    }
    table.insertColumn(columns-1);
    table.insertColumn(columns+1);
    table.setColumnName(columns-1, "percentage");
    table.setColumnName(columns+1, "percentage");
    table.setAlignment(columns-1, Table.RIGHT);
    table.setAlignment(columns+1, Table.RIGHT);
    table.setType(columns-1, Types.CHAR);
    table.setType(columns+1, Types.CHAR);
    DecimalFormat format = new DecimalFormat("#,##0.00%");
    table.setFormat(columns-1, format);
    table.setFormat(columns+1, format);
    for (int i = 0; i < l; ++i) {
      Number value = (Number)table.getValue(i, columns-2);
      if (value != null) {
        table.setValue(i, columns-1, new Double(value.doubleValue()/sum1));
      }
      value = (Number)table.getValue(i, columns);
      if (value != null) {
        table.setValue(i, columns+1, new Double(value.doubleValue()/sum2));
      }
    }
  }

  private void updatePie(Table table) {
    int l = table.getRowCount()-1;
    long sum = 0;
    for (int i = 0; i < l; ++i) {
      Long value = (Long)table.getValue(i, 3);
      if (value != null) sum += value.longValue();
    }
    long other = 0;
    int j = 0;
    for (int i = 0; i < l; ++i) {
      Long value = (Long)table.getValue(i, 3);
      if (value == null || (value.longValue()*2000)/sum < 3) {
        ++j; other += (value == null)? 0 : value.longValue();
      }
    }
    l -= j;
    if (other > 0) {
      ++l; j = 1;
    }
    names = new String[l];
    values = new Long[l];
    if (other > 0) {
      names[0] = "other";
      values[0] = new Long(other);
    }
    l = table.getRowCount()-1;
    for (int i = 0; i < l; ++i) {
      Long value = (Long)table.getValue(i, 3);
      if (value != null && (value.longValue()*2000)/sum >= 3) {
        names[j] = (String)table.getValue(i, 0) + " (" + (String)table.getValue(i, 1) + ')';
        values[j] = (Long)table.getValue(i, 3);
        ++j;
      }
    }
  }

  public static void main(String[] args) {
    if (args.length != 2) {
      System.out.println("USAGE: <name> <password>");
      return;
    }
    try {
      Class.forName("COM.ibm.db2.jdbc.app.DB2Driver").newInstance();
      Connection con = java.sql.DriverManager.getConnection("jdbc:db2:zeta", args[0], args[1]);
      OperatingSystemsHandler handler = new OperatingSystemsHandler(null);
      System.out.println(handler.createPage(con));
    } catch (Exception ex) {
      ex.printStackTrace();
    }
    System.exit(1);
  }

  private final static int imgWidthPie = 600;
  private final static int imgHeightPie = 300;
  private String[] names = null;
  private Long[] values = null;
}