using System;
using System.Collections;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
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() {
            string rst = resubedJob != null ? resubedJob.Query : Session["USQL"] as string;
            if (rst != null && rst != "") {
                rst = Uri.EscapeDataString(rst);
             //   Session["USQL"] = null;
            }
            return rst;
		}
		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;
                    Session["JOB"] = null;
                }
				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() {
            StringBuilder sb = new StringBuilder();
            string[] files = Directory.GetFiles(Server.MapPath("./samples"), "*.sql");          
            sb.AppendLine(MakeContextSamples(Directory.GetFiles(Server.MapPath("./samples"), "*.sql"), "global"));
            foreach (string dir in Directory.GetDirectories(Server.MapPath("./samples"))) {
                files = Directory.GetFiles(dir, "*.sql");
                sb.AppendLine(MakeContextSamples(files, (new DirectoryInfo(dir)).Name));
            }
                
            return sb.ToString();
		}
        static string MakeContextSamples(string[] files, string prefix) {
            StringBuilder sb = new StringBuilder();
            sb.AppendLine("<div id=\""+prefix.ToLower()+"_samples\">");
            foreach (string f in files) {
                string s = (new FileInfo(f)).Name;
                string title = s.Split(',')[1].Split('.')[0].Replace('_', ' ').Trim();
                string id = Math.Abs(f.GetHashCode()).ToString();
                sb.AppendLine("<div><a href=\"#\" onclick=\"setQuery('q_" + id + "');\"" +
                    " onmouseover=\"showSample('q_" + id + "',this);\" onmouseout=\"cjhideqs();\">" + title + "</a></div>");
            }
            sb.AppendLine("</div>");
            return sb.ToString();
        }
		protected string LoadSamplesInfo() {
            StringBuilder sb = new StringBuilder();
            sb.AppendLine(LoadSampleInfoFromDir(Server.MapPath("./samples")));
            foreach (string dir in Directory.GetDirectories(Server.MapPath("./samples")))
                sb.AppendLine(LoadSampleInfoFromDir(dir));
            return sb.ToString();
		}
        static string LoadSampleInfoFromDir(string dir) {
            string[] files = Directory.GetFiles(dir, "*.sql");
            string rst = "";
            foreach (string f in files) {
                string s = (new FileInfo(f)).Name;
                string id = Math.Abs(f.GetHashCode()).ToString();
                string qry = File.ReadAllText(f);
                rst += "<textarea style=\"display:none\" id=\"q_" + id + "\">" + qry + "</textarea>";
            }
            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
	}
}