/*
 * Copyright (C) 1999-2006 <a href="mailto:adrian.paschke@gmx.de">Adrian Paschke</a>
 * 
 * The RBSLM Environment is part of the Rule Based Service Level Agreement (RBSLA)
 * framework, available at 
 * <a href=" http://ibis.in.tum.de/staff/paschke/rbsla/index.htm">RBSLA</a>
 * 
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */

package rbsla.environment.view;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.GradientPaint;
import java.util.Hashtable;

import javax.swing.JComponent;
import javax.swing.JPanel;

import org.apache.log4j.Logger;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.axis.CategoryAxis;
import org.jfree.chart.axis.CategoryLabelPositions;
import org.jfree.chart.axis.NumberAxis;
import org.jfree.chart.plot.CategoryPlot;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.chart.renderer.category.BarRenderer;
import org.jfree.data.category.CategoryDataset;
import org.jfree.data.category.DefaultCategoryDataset;

public class GraphicBarChartViewer implements Viewer
{

    String chartTitle = "Webserver availability";
    String domainAxisName = "";
    String rangeAxisName = "Availabilty (%)";
    String series1 = "Should";
    String series2 = "Is";
    String category1 = "Main Time";
    String category2 = "Service Time";

    private static Logger logger = Logger
            .getLogger(GraphicBarChartViewer.class);

    private BarChartPanel barChartPanel;
    private Hashtable viewerProperties;

    public Hashtable getViewerPropertieNames()
    {
        Hashtable barChartViewerProperties;
        barChartViewerProperties = new Hashtable();
        barChartViewerProperties.put("Chart Title", chartTitle);
        barChartViewerProperties.put("Domain Axis", domainAxisName);
        barChartViewerProperties.put("Range Axis", rangeAxisName);
        barChartViewerProperties.put("Category A", category1);
        barChartViewerProperties.put("Category B", category2);
        barChartViewerProperties.put("Serie 1", series1);
        barChartViewerProperties.put("Serie 2", series2);
        return barChartViewerProperties;
    }

    public JComponent getContentPane(Hashtable viewerProperties)
    {
        chartTitle = (String) viewerProperties.get("Chart Title");
        domainAxisName = (String) viewerProperties.get("Domain Axis");
        rangeAxisName = (String) viewerProperties.get("Range Axis");
        category1 = (String) viewerProperties.get("Category A");
        category2 = (String) viewerProperties.get("Category B");
        series1 = (String) viewerProperties.get("Serie 1");
        series2 = (String) viewerProperties.get("Serie 2");
        
        barChartPanel = new BarChartPanel(""); //this.getTitle()
        return barChartPanel;
    }

    public void dataChanged(String result, String debugText)
    {

    	String parseResult = ParseResults.instance().parseManyResults(result);
    	
    	String [] numbers = parseResult.split("\\,");
    	
    	double [] numbersDouble = new double [] {0.0,0.0,0.0,0.0};
    	for (int i = 1; i <= 4; i++)
    	    try  {
    	        numbersDouble[i-1] = new Double(numbers[i]).doubleValue();
    	        if (Double.isInfinite(numbersDouble[i-1]) || Double.isNaN(numbersDouble[i-1]))
    	            numbersDouble[i-1] = 0.0;
    	        
    	    } catch (Throwable ex) {
    	        // do not do anything ...
    	    }
      	logger.info("Number: " + new Double(numbersDouble[0]) + " " + new Double(numbersDouble[1]) + " " + new Double(numbersDouble[2]) + " "+ new Double(numbersDouble[3]) );

    	// create the dataset...
        DefaultCategoryDataset dataset = new DefaultCategoryDataset();

        dataset.addValue(numbersDouble[0], series1, category1);
        dataset.addValue(numbersDouble[1], series2, category1);

        dataset.addValue(numbersDouble[2], series1, category2);
        dataset.addValue(numbersDouble[3], series2, category2);

        barChartPanel.changeDataset(dataset, chartTitle, domainAxisName, rangeAxisName);
    }
}

class BarChartPanel extends JPanel
{

    private ChartPanel chartPanel;
    private JFreeChart chart;


    public BarChartPanel(String title)
    {
        super(new BorderLayout());
        CategoryDataset dataset = new DefaultCategoryDataset();
        chart = createChart(dataset, "", "", "");
        chartPanel = new ChartPanel(chart);
        chartPanel.setPreferredSize(new Dimension(500, 270));
        add(chartPanel);
        
    }
   

    public void changeDataset(CategoryDataset dataset, String chartTitle, String domainAxisName, String rangeAxisName)
    {
        chartPanel.setChart(createChart(dataset, chartTitle, domainAxisName, rangeAxisName));
        chartPanel.repaint();

    }

    private JFreeChart createChart(CategoryDataset dataset,  String chartTitle, String domainAxisName, String rangeAxisName)
    {

        // create the chart...
        JFreeChart chart = ChartFactory.createBarChart(
                chartTitle, // chart
                                                                 // title
                domainAxisName, // domain axis label
                rangeAxisName, // range axis label
                /*
                 * "Reaktion des Kundenservices (Dezember 2004)", // chart
                 * title "", // domain axis label "Zeit (Minuten)", // range
                 * axis label
                 */
                dataset, // data
                PlotOrientation.VERTICAL, // orientation
                true, // include legend
                true, // tooltips?
                false // URLs?
                );

        // set the background color for the chart...
        chart.setBackgroundPaint(Color.white);

        // get a reference to the plot for further customisation...
        CategoryPlot plot = chart.getCategoryPlot();
        plot.setBackgroundPaint(Color.lightGray);
        plot.setDomainGridlinePaint(Color.white);
        plot.setDomainGridlinesVisible(true);
        plot.setRangeGridlinePaint(Color.white);

        // set the range axis to display integers only...
        final NumberAxis rangeAxis = (NumberAxis) plot.getRangeAxis();
        rangeAxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits());

        rangeAxis.setRangeWithMargins(0.0,1.0);
        // disable bar outlines...
        BarRenderer renderer = (BarRenderer) plot.getRenderer();
        renderer.setDrawBarOutline(false);

        // set up gradient paints for series...
        GradientPaint gp0 = new GradientPaint(0.0f, 0.0f, Color.blue, 0.0f,
                0.0f, new Color(0, 0, 64));
        GradientPaint gp1 = new GradientPaint(0.0f, 0.0f, Color.green,
                0.0f, 0.0f, new Color(0, 64, 0));
        GradientPaint gp2 = new GradientPaint(0.0f, 0.0f, Color.red, 0.0f,
                0.0f, new Color(64, 0, 0));
        renderer.setSeriesPaint(0, gp0);
        renderer.setSeriesPaint(1, gp1);
        //renderer.setSeriesPaint(2, gp2);

        CategoryAxis domainAxis = plot.getDomainAxis();
        domainAxis.setCategoryLabelPositions(CategoryLabelPositions
                .createUpRotationLabelPositions(Math.PI / 6.0));

        return chart;

    }


}


