package com.jware.common.charts;

import java.io.*;
import java.io.IOException;

import org.jCharts.Chart;
import org.jCharts.encoders.*;

abstract class BaseChart {

   private String chart_file_type = "png";


   public void set_chart_file_type ( String chart_file_type ) {
     this.chart_file_type = chart_file_type;
   }
   public String get_chart_file_type () {
     return chart_file_type;
   }

	/******************************************************************************************
	* Utility method to write the image to file so I do not have to deal with file i/o
	*  every time I write a demo.
	*
	* @param exportableImage verything that is renderable extends this class.
	* @param fileName what to name the file
	* @throws Throwable
	******************************************************************************************/

	void exportImage( Chart chart, String fileName )
	{
          if ( chart_file_type == null || chart_file_type.compareToIgnoreCase("jpg") == 0 )
            exportImageJPEG( chart, fileName );
          else if ( chart_file_type.compareToIgnoreCase("png") == 0 )
            exportImagePNG( chart, fileName );
          else if ( chart_file_type.compareToIgnoreCase("svg") == 0 )
            exportImageSVG( chart, fileName );
          else
            exportImageJPEG( chart, fileName );

        }

	void exportImagePNG( Chart chart, String fileName )
	{
	   String extension= ".png";
		FileOutputStream fileOutputStream;

		try
		{
			fileOutputStream= new FileOutputStream( fileName + extension );
                        PNGEncoder.encode( chart, fileOutputStream );
			fileOutputStream.flush();
			fileOutputStream.close();
		}
		catch( IOException ioException )
		{
			ioException.printStackTrace();
		}
	}

	void exportImageJPEG( Chart chart, String fileName )
	{
	   String extension= ".jpg";
		FileOutputStream fileOutputStream;

		try
		{
			fileOutputStream= new FileOutputStream( fileName + extension );
                        JPEGEncoder13.encode( chart, 1f, fileOutputStream );
			fileOutputStream.flush();
			fileOutputStream.close();
		}
		catch( IOException ioException )
		{
			ioException.printStackTrace();
		}
	}

	void exportImageSVG( Chart chart, String fileName )
	{
	   String extension= ".svg";
		FileOutputStream fileOutputStream;

		try
		{
			fileOutputStream= new FileOutputStream( fileName + extension );
                        SVGEncoder.encode( chart, fileOutputStream );
			fileOutputStream.flush();
			fileOutputStream.close();
		}
		catch( IOException ioException )
		{
			ioException.printStackTrace();
		}
	}

}
