/*	ZssChartEngine.java

	Purpose:
		
	Description:
		
	History:
		Oct 18, 2010 2:27:40 PM     2010, Created by henrichen

	Copyright (C) 2010 Potix Corporation. All Rights Reserved.
*/

package org.zkoss.zssex.util;

import org.jfree.chart.JFreeChart;
import org.jfree.chart.block.BlockBorder;
import org.jfree.ui.RectangleEdge;
import org.zkoss.zkex.zul.impl.JFreeChartEngine;
import org.zkoss.zss.model.SChart;
import org.zkoss.zul.Chart;

/**
 * A ZssChartEngine customized to draw Chart for matching Excel chart style
 * 
 * @author henrichen@zkoss.org
 * @author dennis , refine to new chart model
 */
public class ZssChartEngine extends JFreeChartEngine {
	final protected SChart _chartInfo;
	private static final long serialVersionUID = 201011021111L;
	static final int POS_B = 1;
	static final int POS_TR = 2;
	static final int POS_L = 3;
	static final int POS_R = 4;
	static final int POS_T = 5;

	public ZssChartEngine(SChart chartInfo) {
		_chartInfo = chartInfo;
	}
	
	public boolean prepareJFreeChart(JFreeChart jfchart, Chart chart) {
		chart.setPaneColor("#FFFFFF"); //set the chart background to WHITE (was #EEEEEE, light gray)
//		chart.setSclass("chartborder");
		//jfchart.setBorderVisible(true); //draw the chart outline
		jfchart.getPlot().setOutlineVisible(false); //DO NOT draw the plot outline
		jfchart.getLegend().setFrame(BlockBorder.NONE); //remove legend boarder
		
		// ZSS-140: check legend first
		if(hasLegend()) {
			RectangleEdge edge = null; 
			switch(getLegendPos()) {
				case POS_B:
					edge = RectangleEdge.BOTTOM;
					break;
				case POS_L:
					edge = RectangleEdge.LEFT;
					break;
				case POS_T:
					edge = RectangleEdge.TOP;
					break;
				case POS_TR: //TODO corner not supported
				case POS_R:
				default:
					edge = RectangleEdge.RIGHT;
					break;
			}
			jfchart.getLegend().setPosition(edge); //put legend on the right
		} else {
			// ZSS-140: handle not legend case
			jfchart.getLegend().setVisible(false);
		}
		//ZSS-822
		JFreeChartHelper.prepareAxis(jfchart, _chartInfo);
		return false;
	}
	
	// ZSS-140: for testing legend existed or not
	private boolean hasLegend() {
		return _chartInfo.getLegendPosition()!=null;
	}
	
	private int getLegendPos() { //r, l, t, b
		switch(_chartInfo.getLegendPosition()) {
			case BOTTOM:
				return POS_B;
			case LEFT:
				return POS_L;
			case TOP:
				return POS_T;
			case TOP_RIGHT:
				return POS_TR;
			case RIGHT:
			default:
				return POS_R;
			}
	}
}