using System;
using System.Collections;
using System.Data;

using edu.jhu.Cas.Jobs;

namespace edu.jhu.Cas.Util
{
	/// <summary>
	/// Summary description for ImgInterface.
	/// </summary>
	public class ImgInterface
	{
		ImgCutout cutout;
		public ImgInterface()
		{
			cutout = new ImgCutout();
		}

		/*
		 * returns zip filename
		 */
		public string FetchAndPack(long wsid, DataSet ds,string path,string fileName){
			return FetchAndPack(wsid,ds,path,fileName,new ImgCutoutParams());
		}
		public string FetchAndPack(long wsid, string tableName,string path,string fileName){
			DataSet ds = (new CasJobs()).SubmitShortJob(wsid,"select * from "+tableName,
				"MYDB",SYSTEM.TASKNAME+" CUTOUT",0);
			return FetchAndPack(wsid,ds,path,fileName,new ImgCutoutParams());
		}
		public string FetchAndPack(long wsid, DataSet ds,string path,string fileName,ImgCutoutParams args){
			object[] ra,dec;
			try{
				ra = DataSetUtils.ColumnValues(ds,"ra");
				dec = DataSetUtils.ColumnValues(ds,"dec");
			}catch(Exception e){
				e=e;
				throw new Exception("Table does not contain ra and dec columns");
			}
			int hasScale = DataSetUtils.ColumnIndex(ds,"scale");
			object[] scale = null;
			if(hasScale != -1)
				scale = DataSetUtils.ColumnValues(ds,"scale");
			ZipFile zip = new ZipFile(path+fileName);
			for(int x=0;x<ra.Length;x++){
				double s = IMG.SCALE;
				if(scale != null)
					s = (double)scale[x];
				byte[] anImage = Fetch((double)ra[x],(double)dec[x],s,args);
				string fName = ra[x].ToString().Replace(".","_")+"_"+dec[x].ToString().Replace(".","_")+".jpg";
				zip.AddBytes(anImage,fName);
			}
			zip.Complete();
			return fileName;
			
		}

		public byte[] Fetch(double ra, double dec, double scale,ImgCutoutParams args){
		/**
			IAsyncResult aResult = cutout.BeginGetJpeg(ra,dec,scale,width,height,"",null,null);
			aResult.AsyncWaitHandle.WaitOne();
			*/
			return cutout.GetJpeg(ra,dec,scale,args.Width,args.Height,args.Opt);
		}
	
	}
}
