using System;
using System.Collections;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using edu.jhu.Cas.Jobs;
using edu.jhu.Cas.Util;
using edu.jhu.Cas.Servers;
using System.Text;
using System.Diagnostics;
using System.IO;
using System.Data.SqlClient;
namespace edu.jhu.Cas.Web {

    public class SubmitJobHelper : System.Web.UI.Page {
		protected Hashtable tList = null;
		protected System.Web.UI.WebControls.DataGrid grid;
		protected DataSet ds,hist,loads;
		protected bool loggedin =false,syntax=false;
		protected long wsid;
        protected long jobid = -1;
		protected long serviceid = edu.jhu.Cas.Util.ID.SERVICE_ID;
		protected bool submitted = false;
		protected bool debug;
		protected bool showResult = false;
		protected Job resubedJob = null;
		protected string cpuUsed = "";
		protected string tableLink = "";

        protected string message,mclass;
        protected override void OnUnload(EventArgs e) {}
        static readonly char[] TRIM_CHARS = new char[] { ' ', '\n', '\r', '\t' };
		
        protected StringCollection sList;
        private void CheckSyntax(string qry, string context) {
            if (qry == null || qry.Length < 3) {
                message = "Please enter a query.";
                return;
            }
            message = (new CasJobs()).CheckSyntax(wsid, qry, context);
            if (message == null) {
                message = "Syntax OK";
                mclass = "happy";
            }
            else
                mclass = "error";
        }
		private void Page_Load(object sender, System.EventArgs EE) {
            try {
                Response.ContentType = "text/xml";
                string qry = Request.Params["sql"];
                //if(qry != null)qry = qry.Replace("P_L_U_S", "+");
                string targ = Request.Params["targest"];
                if(targ != null)
                    targ = targ.Trim(TRIM_CHARS);

                if (Session["USER"] != null)
                    wsid = (long)Session["USER"];
                else
                    throw new Exception("Your session has timed-out.  Please login again.");
                if (Request.Params["syntax"] == "true") {//check syntax
                    CheckSyntax(qry,targ );
                    return;
                }
                if (qry != null && qry.Length < 9 && qry.ToUpper().Trim().CompareTo("DEBUG") == 0) {//enable debug mode
                    string old = Session["DEBUG"].ToString();
                    Session["DEBUG"] = old.CompareTo("true") == 0 ? "false" : "true";
                    message = "DEBUG: " + Session["DEBUG"];
                    mclass = "error";
                    return;
                }

                //load parameters
                string table = Request.Params["table"];
                if (table != null)
                    table = table.Trim(TRIM_CHARS);
                string taskname = Request.Params["taskname"];
                if(taskname != null)
                    taskname = taskname.Trim(TRIM_CHARS);
                int q = Request.Params["queue"] != null?int.Parse(Request.Params["queue"]):-1;
                if (q == -1) return;
                               
                //if necessary, modify parameters
                CasServers cServers = new CasServers();
                if (taskname == null || taskname.Length == 0) taskname = SYSTEM.DEFAULT_QUERY_NAME;
                q = cServers.ClosestQueue(edu.jhu.Cas.Util.ID.SERVICE_ID,wsid, targ, q).Queue;

                bool isquick = cServers.IsInLowestQueue(wsid, q, targ);

                if (!isquick && table != null && table != "" && table.Length > 1) {
                    FilterFactory ff = new FilterFactory();
                    qry = ff.StripComments(qry);
                    qry = ff.AddSelectInto(qry, table, targ);
                }
                edu.jhu.Cas.Jobs.CasJobs job = new edu.jhu.Cas.Jobs.CasJobs();
                //run it
                if (isquick) {
                    ds = job.SubmitShortJob(wsid, qry, targ, taskname, 0);
                    Session[edu.jhu.Cas.Output.VODataClean.RST] = ds;
                    mclass = "happy";
                    message = "Fetching results...";
                }
                else {
                    if (taskname == null || taskname.Length == 0) taskname = SYSTEM.DEFAULT_QUERY_NAME;
                    jobid = job.SubmitJob(wsid, qry, targ, taskname, q, 0);
                    mclass = "happy";
                    message = "Job " + jobid + " submitted.";
                }
            }
            catch(Exception e) {
                mclass = "error";
                message = System.Web.HttpUtility.UrlEncode(Exception2Message(e));
            }            
		}
        const int MAXQRYCHARS = 110;
        const int HIST_LENGTH = 10;
        protected string getHist() {
            DataSet ds = (new CasJobs()).FindJobWithStatusDataSet(wsid, HIST_LENGTH, 0, "jobid, taskname, query", "", false, -1);
            StringBuilder sb = new StringBuilder();
            sb.AppendLine("<div class=\"alt\">");
            sb.AppendLine("<table cellpadding=\"0\" cellspacing=\"1\" style=\"white-space:nowrap\" id=\"histTab\">");
            sb.AppendLine("<tr><th>Name</th><th>Query</th></tr>");
            foreach (DataRow dr in ds.Tables[0].Rows) {
                string qry = dr["query"] as string;
                if (qry != null && qry.Length > MAXQRYCHARS)
                    qry = qry.Substring(0, MAXQRYCHARS)+"...";
                sb.AppendLine("<tr><td style=\"cursor:pointer\"><a onclick=\"setQuery('rq" + dr["jobid"] + "');\" style=\"padding:0 2 0 1; cursor:pointer\">" + dr["taskname"] + "</a></td><td>" +
                    qry + "</td></tr>");
            }
            sb.AppendLine("</table>");
            foreach (DataRow dr in ds.Tables[0].Rows) {
                sb.AppendLine("<textarea style=\"display:none\" id=\"rq" + dr["jobid"] + "\">"+dr["query"]+"</textarea>");
            }
            sb.AppendLine("</div>");
            return HttpUtility.UrlEncode(sb.ToString());
        }
        private string Exception2Message(Exception e) {
            if (debug) {
                return e.ToString();
            }   
            else {
                return e.Message;
            }
        }

		#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);
		}
        protected override void OnError(EventArgs e) {
            //base.OnError(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);
		}
		#endregion
	}
}