using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Xml;
using System.Xml.Serialization;
using net.ivoa;
using net.ivoa.adql;
using net.ivoa.data;
using net.ivoa.VOTable;
using edu.jhu.Cas.Util;
//using net.ivoa.SkyPortal;
namespace edu.jhu.Cas.Output {
	public class VODataClean : System.Web.UI.Page {
		protected bool isHTML = false;
		protected string html;
		public const int CELL_CAP = 10000;
		public string rArgs = null;
		protected DataWrapper data,smalldata;
        protected bool noresults = false;
		public const string RST = "QUERY_RESULTS",SRST="SMALL_QUERY_RESULTS";
		
		private void Page_Load(object sender, System.EventArgs e) {
            if (Session[RST] == null) {
                noresults = true;
                return;
            }
            bool doSave = Request.Params["save"] != null && Request.Params["save"].CompareTo("true") == 0;			
			bool noCap =  (Request.Params["cap"] != null && Request.Params["cap"].CompareTo("false") == 0) || doSave;			
			string type = Request.Params["type"];
			type = type != null?type:"HTML";
			DataSet ds = (DataSet)Session[RST];
            int origRows = ds.Tables.Count > 0?ds.Tables[0].Rows.Count:0;
			if(doSave){
				data = WrapperFactory.GetDataWrapper(ds);
				Response.ContentType = "application/octet-stream";
				DateTime t = DateTime.Now;
				string fileName = "MyResult_"+t.Year+t.Month+t.Day;
				switch(type){
					case "DATASET":fileName+=".xml";break;
					case "HTML":fileName+=".html";break;
					case "CSV":fileName+=".csv";break;
					case "VOTABLE":fileName+=".xml";break;
				}
				Response.AppendHeader( "content-disposition", "attachment; filename="+fileName);
			}else{
				smalldata = WrapperFactory.GetDataWrapper(ds.Copy());
				smalldata.RowCap = (int)(CELL_CAP/smalldata.ColCount);
				Session[SRST] = smalldata;
				data = smalldata;
			}
			switch(type.ToUpper()){
				case "DATASET":
					DataSet dds = DataSetWrapper.Wrapper2DataSet(data);
					XmlSerializer s = new XmlSerializer(typeof(DataSet));
					StringWriter sw = new StringWriter();
					s.Serialize(sw,ds);
					string output = sw.ToString();
					output =output.Replace("encoding=\"utf-16\"","encoding=\"utf-8\"");
					if(!doSave)Response.ContentType = "text/xml";
					Response.Write(output);
					break;	
				case "HTML":
					isHTML = true;
                    html = "";
					if(!doSave){
						html+= "<p id=\"wholething\" style=\"font-style:italic\">";
						if(origRows > data.RowCount)
							html+= "Only the first "+data.RowCount+" of "+origRows+" rows are displayed for this query.  Please click 'Save' to get all "+origRows+" rows.";
						else
							html +=origRows+" row(s)";
						html+="</p>";
					}
					html+= "<div id=\"data_table\">"+WrapperFactory.Wrapper2HTML(data,"rsttable","alt",null,null,"alt","0","0", doSave?WrapperFactory.NOMAXCHARS:SYSTEM.MAX_HTML_DATA_CHARS)+"</div>";
					break;
				case "CSV":
					isHTML = !doSave;
					string newline = doSave?WrapperFactory.UNIX_NEWLINE:
						WrapperFactory.HTML_NEWLINE; 
					Response.Write(WrapperFactory.Wrapper2CSV(data,newline));
					break;
				case "VOTABLE":
					VOTABLE vot = VOTableWrapper.Wrapper2VOTable(data);
					XmlSerializer vs = new XmlSerializer(typeof(VOTABLE));
					StringWriter vsw = new StringWriter();
					vs.Serialize(vsw,vot);
					string vout =vsw.ToString();
					vout = vout.Replace("encoding=\"utf-16\"","encoding=\"utf-8\"");
					if(!doSave)Response.ContentType = "text/xml";
					Response.Write(vout);
					break;
			}
			return;
		}
		#region Web Form Designer generated code
		override protected void OnInit(EventArgs e) {
			//
			// CODEGEN: This call is required by the ASP.NET Web Form Designer.
			//
			InitializeComponent();
			base.OnInit(e);
		}
		
		/// <summary>
		/// Required method for Designer support - do not modify
		/// the contents of this method with the code editor.
		/// </summary>
		private void InitializeComponent() {    
			this.Load += new System.EventHandler(this.Page_Load);
		//	this.Unload += new System.EventHandler(this.Page_UnLoad);
		}
		#endregion
	}
}
