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.Diagnostics;
using System.IO;
using System.Data.SqlClient;
namespace edu.jhu.Cas.Web {
	/// <summary>
	/// This is the code behind ffor the submit job aspx page. It does a few things for
	/// the interface like finding unique table names and facilitating resubmit using the
	/// JOB n the session to get the details from. The aspx may also be called as a CGI
	/// passing sql= target= etc. on the url.
	/// </summary>
	public class SubmitJob : System.Web.UI.Page {
		
		protected Hashtable tList = null;
		protected bool loggedin =false,syntax=false;
		protected long wsid;
		protected long serviceid = edu.jhu.Cas.Util.ID.SERVICE_ID;	
		protected Job resubedJob = null;
        protected string message = null;

        protected override void OnUnload(EventArgs e) {
        }
		/// <summary>
		/// we could get the target as a reuest varibale or via a resubmitted job - or neither
		/// </summary>
		/// <param name="targ"></param>
		/// <returns></returns>
        protected string targisselected(string targ) {
			if(Request.Params["targest"] != null)
				return (Request.Params["targest"].CompareTo(targ) == 0)?"SELECTED=\"SELECTED\"":"";
			else 
			{
				if (null != resubedJob) 
				{
					return (resubedJob.Target.CompareTo(targ) == 0)?"SELECTED=\"SELECTED\"":"";
				}
			}
			return "";
		}
		protected string GetQuery() {
            return resubedJob != null ? resubedJob.Query : Session["USQL"] as string;
			//return resubedJob != null?resubedJob.Query:HttpUtility.HtmlDecode(Request.Params["sql"]);
		}
        protected StringCollection sList;
		private void Page_Load(object sender, System.EventArgs e) {
            message = Request.Params["lmessage"];
            try {
                if (Request.Params["resubmit"] != null) resubedJob = Session["JOB"] as Job;
                
                WebUtils.CheckLoggedIn(Session, Response, Request);
                loggedin = Session["USER"] != null;
                if (loggedin) wsid = (long)Session["USER"];
                

                Server[] sOrdered = (new CasJobs()).ListServers(wsid);
                CasServers cs = new CasServers();
                tList = new Hashtable();
                sList = new StringCollection();
                ArrayList tmp = new ArrayList();

                for (int s = 0; s < sOrdered.Length; s++) {
                    Server ss = sOrdered[s];
                    if (tList.Contains(sOrdered[s].Target)) {
                        ((ArrayList)tList[sOrdered[s].Target]).Add(sOrdered[s]);
                    }
                    else {
                        sList.Add(ss.Target);
                        ArrayList al = new ArrayList();
                        al.Add(sOrdered[s]);
                        tList.Add(sOrdered[s].Target, al);
                    }
                }
            }
            catch (Exception ee) {
                //these should generally never show up
                message = ee.Message;
            }
		}
		
		protected string GetUniqueTableName(){
			return WebUtils.GetUniqueTableName(wsid);
		}
 		/// <summary>
		/// task name might be in the request or a resubmited job - or we do thedefault
		/// </summary>
		/// <returns></returns>
		protected string getTaskName(){
			if (resubedJob !=null) 
				return resubedJob.TaskName;
			if (Request.Params["taskname"] != null)
				return Request.Params["taskname"];
			return 	SYSTEM.DEFAULT_QUERY_NAME;
		}
        protected string LoadSamples() {
            string[] files = Directory.GetFiles(Server.MapPath("./samples"),"*.sql");
            string rst = "<table id=\"squeries\" style=\"width:100%;\" cellpadding=\"0\" cellspacing=\"0\">";
            foreach (string f in files) {
                string s = (new FileInfo(f)).Name;
                string title = s.Split(',')[1].Split('.')[0].Replace('_', ' ').Trim();
                string id = s.Split(',')[0];
                string desc = File.ReadAllText(f.Replace(".sql",".desc"));
                string qry = File.ReadAllText(f);
                rst += "<tr><td style=\"text-align:left;\"><a href=\"#\" onclick=\"setQuery('q_"+id+"');\"" +
                    " onmouseover=\"cjshowqs('qd_"+id+"',this);\" onmouseout=\"cjhideqs();\">"+title+"</a></td>";
                rst += "</tr>";
            }
            rst += "</table>";
            return rst;
        }
        protected string LoadSamplesInfo() {
            string[] files = Directory.GetFiles(Server.MapPath("./samples"), "*.sql");
            string rst = "";
            foreach (string f in files) {
                string s = (new FileInfo(f)).Name;
                string id = s.Split(',')[0];
                string desc = File.ReadAllText(f.Replace(".sql", ".desc"));
                string qry = File.ReadAllText(f);
                rst += "<textarea style=\"display:none\" id=\"q_" + id + "\">" + qry + "</textarea>";
                rst += "<div class=\"qpop\" id=\"qd_" + id + "\">" + desc + "</div>";
                //rst += "<div id=\"qd_" + id + "\">" + desc + "</div>";
            }
            return rst;
        }
		#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);
		}
		#endregion
	}
}