using System;
using System.Collections;
using System.Data;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.IO;
using SoftwareFX.ChartFX.Lite;
using edu.jhu.Cas.Jobs;
namespace edu.jhu.Cas.Util {
	/// <summary>
	/// Summary description for Plot.
	/// </summary>
	public class PlotInterface {
	
		public string path = "\\\\skyservice\\skyservice\\CasOutput\\Plot\\";
		public string url = "http://skyservice.pha.jhu.edu/CasOutput/Plot/";
		
		public PlotInterface() {
			//
			// TODO: Add constructor logic here
			//
		}
		public string PlotTable(long wsid, string tableName){
			return PlotTable(wsid,tableName,new PlotArgs());
		}
		public string PlotTable(long wsid, string tableName, PlotArgs args){
			DataSet ds = (new MyDBJobs()).PreviewTable(wsid,tableName,PLOT.ROW_LIMIT,"MYDB");
			Chart chart = MakePlot(ds,args);
			return SavePlotAs(chart,wsid+"_"+tableName+".jpg");
		}
		public Chart MakePlot(DataSet ds, PlotArgs args){
			Console.WriteLine("HERE");
			Chart chart = new Chart();
			chart.Location = new System.Drawing.Point(8, 8);
			chart.Size = new System.Drawing.Size(args.Width,args.Height);
			chart.TabIndex = 0;
			
			//chart.DataSource = ds.Tables[0];
			args.Series = CheckSeries(args.Series,ds);
			chart.OpenData(COD.Values,args.Series.Length,ds.Tables[0].Rows.Count);
			Console.WriteLine("HERE");
			for(int x=0;x<args.Series.Length;x++){
				object[] rows = DataSetUtils.ColumnValues(ds,args.Series[x]);
				for(int y=0; y<rows.Length;x++)
					chart.Value[x,y] = double.Parse(rows[y].ToString());
			}
			chart.CloseData(COD.Values);
			chart.Gallery = args.Type;
			chart.SerLegBox = args.ShowLegend;
			return chart;
		}
		/**
		 * returns url of saved plot
		 */
		public string SavePlotAs(Chart chart,string name){
			int width = chart.Size.Width;
			int height = chart.Size.Height;
			Bitmap bMap = new Bitmap(width,height);
			Graphics g = Graphics.FromImage(bMap);
			g.FillRectangle(new SolidBrush(Color.WhiteSmoke), 
				0,0,(float)width, (float)height);
			g.SmoothingMode = SmoothingMode.AntiAlias;
			chart.Paint(g,new Rectangle(0,0,width,height),
				SoftwareFX.ChartFX.Lite.Base.PaintFlags.Normal);
			FileStream fs = File.Create(path+name);
			bMap.Save(fs,ImageFormat.Jpeg);
			fs.Close();
			return url+name;
		}
		protected string[] CheckSeries(string[] series, DataSet ds){
			if(series == null){
				string[] rst = new string[ds.Tables[0].Columns.Count];
				for(int x=0;x<rst.Length;x++)
					rst[x] = ds.Tables[0].Columns[x].ColumnName;
				return rst;
			}else
				return series;
		}
	}
	//defaults are here
	public class PlotArgs{
		public int Width, Height;
		public Gallery Type;
		public bool ShowLegend;
		public string Query;
		public string title;
		public string[] Series;//names of columns
		
		public PlotArgs(){
			Width = 800;
			Height = 600;
			Type = Gallery.Scatter;
			ShowLegend = true;
		}
	}
}
