using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
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;



namespace edu.jhu.Cas.Web {
    /// <summary>
    /// Summary description for ViewJobs.
    /// </summary>
    public class ViewJobs : System.Web.UI.Page {
        protected DataGrid grid;
        protected DataSet ds;
        protected string lmessage;
        private long wsid;
        protected int setSize, position;
        protected int totalSetLinks, x;
        private static int defaultSetSize = 50;
        protected DropDownList statusDdl, targetDdl, sinceDdl;
        private string whereClause;

        protected System.Web.UI.WebControls.Button filterButton;
        protected string stupidVariable;
        protected System.Web.UI.WebControls.TextBox nameBox;

        private void Page_Load(object sender, System.EventArgs e) {

        }




        public void LoadMenus() {

            statusDdl.Items.Add(new ListItem("ANY"));
            targetDdl.Items.Add(new ListItem("ANY"));
            DataSet statusSet = SqlFactory.select("select distinct text from status");
            DataColumn c = statusSet.Tables[0].Columns[0];
            foreach (DataRow r in statusSet.Tables[0].Rows)
                statusDdl.Items.Add(new ListItem(r[c].ToString()));

            DataSet targetSet = SqlFactory.select("select distinct target from jobs where webservicesid = " + wsid);
            DataColumn c2 = targetSet.Tables[0].Columns[0];
            foreach (DataRow r in targetSet.Tables[0].Rows)
                targetDdl.Items.Add(new ListItem(r[c2].ToString()));

            sinceDdl.Items.Add(new ListItem("Today", DateTime.Today.ToString()));
            sinceDdl.Items.Add(new ListItem("This Week", DateTime.Today.AddDays(-6).ToString()));
            sinceDdl.Items.Add(new ListItem("This Month", DateTime.Today.AddMonths(-1).ToString()));
            sinceDdl.Items.Add(new ListItem("All"));
            sinceDdl.SelectedIndex = sinceDdl.Items.IndexOf(sinceDdl.Items.FindByText(Session[VIEWJOBS.TIME_SUBMIT].ToString()));
            statusDdl.SelectedIndex = statusDdl.Items.IndexOf(statusDdl.Items.FindByText(Session[VIEWJOBS.STATUS].ToString()));
            targetDdl.SelectedIndex = targetDdl.Items.IndexOf(targetDdl.Items.FindByText(Session[VIEWJOBS.TARGET].ToString()));
            nameBox.Text = Session[VIEWJOBS.NAME_LIKE].ToString();
        }

        protected void ReLoadGrid(object sender, System.EventArgs e) {
            Session[VIEWJOBS.TIME_SUBMIT] = sinceDdl.SelectedItem.Text;
            Session[VIEWJOBS.STATUS] = statusDdl.SelectedItem.Text;
            Session[VIEWJOBS.TARGET] = targetDdl.SelectedItem.Text;
            Session[VIEWJOBS.NAME_LIKE] = nameBox.Text;
            Session[VIEWJOBS.POSITION] = 0;
            Response.Redirect("ViewJobs.aspx");
        }

        protected void LoadWhereClause() {
            Stack args = new Stack();
            if (Session[VIEWJOBS.STATUS].ToString().CompareTo("ANY") != 0) {
                int status = int.Parse(SqlFactory.scalar(
                    "select status from status where text = '" + statusDdl.SelectedItem.Text + "'").ToString());
                args.Push(" j.status = '" + status + "'");
            }
            //if(typeDdl.SelectedItem.Text.CompareTo("ANY") != 0)
            //	args.Push(" outputtype = '"+typeDdl.SelectedItem.Text+"'");
            if (Session[VIEWJOBS.TARGET].ToString().CompareTo("ANY") != 0)
                args.Push(" target = '" + targetDdl.SelectedItem.Text + "'");
            if (Session[VIEWJOBS.NAME_LIKE].ToString().Length > 0)
                args.Push(" taskname like '%" + nameBox.Text + "%' ");
            //if(Session[VIEWJOBS.TIME_SUBMIT].ToString().CompareTo("All") != 0)
            //	args.Push(" timesubmit > CAST('"+sinceDdl.SelectedItem.Value.ToString()+"' as datetime)");
            args.Push(" visibility = " + VISIBILITY.USER_VISIBLE);
            args.Push(" outputtype = '" + OUTPUT.QUERY + "' ");
            whereClause = "";
            while (args.Count > 1)
                whereClause += args.Pop().ToString() + " and ";
            if (args.Count == 1)
                whereClause += args.Pop().ToString();
        }

        protected void LoadGrid(object sender, System.EventArgs e) {

            LoadWhereClause();
            edu.jhu.Cas.Jobs.CasJobs job = new edu.jhu.Cas.Jobs.CasJobs();
            string seconds = "datepart(ss,timeend - timestart)";
            string minutes = "datepart(mi,timeend - timestart)";
            string hours = "datepart(hh,timeend - timestart)";

            string timeclause = " convert(varchar, " + hours + ")+':'+convert(varchar, " + minutes + ")+':'+convert(varchar," + seconds + ") as elapsed ";
            string tqclause = " (rtrim(convert(char,target))+'/'+rtrim(convert(char,estimate)))as tq ";
            ds = new DataSet();

            ds = job.FindJobWithStatusDataSet(wsid, setSize, position, @"jobid,taskname,timesubmit,outputtype,target,rows,estimate,query,
				hostip as machine,html as status," + timeclause + "," + tqclause, whereClause, false, 60);
            DataSet count = job.FindJobWithStatusDataSet(wsid, setSize, -1, @"jobid,taskname,timesubmit,outputtype,target,rows,estimate,query,
				hostip as machine,html as status," + timeclause + "," + tqclause, whereClause, true, 30);
            int cc = int.Parse(count.Tables[0].Rows[0][0].ToString());
            totalSetLinks = cc / setSize;
            if (cc % setSize != 0) totalSetLinks++;

            for (int r = 0; r < ds.Tables[0].Rows.Count; r++)
                for (int c = 0; c < ds.Tables[0].Columns.Count - 5; c++)
                    if (ds.Tables[0].Rows[r][c] is string && ds.Tables[0].Rows[r][c].ToString().Length > 30)
                        //throw new Exception(ds.Tables[0].Rows[r][c].ToString());
                        ds.Tables[0].Rows[r][c] = ds.Tables[0].Rows[r][c].ToString().Substring(0, 30);


            grid.DataSource = ds.Tables[0];
            grid.DataBind();
            System.Web.UI.WebControls.Table t = (System.Web.UI.WebControls.Table)grid.Controls[0];
            for (int y = 0; y < t.Rows.Count; y++) {
                t.Rows[y].Attributes.Add("height", "2px");
                for (int x = 0; x < t.Rows[y].Cells.Count; x++) {
                    if (y == 0)
                        t.Rows[y].Cells[x].Attributes.Add("align", "center");
                    else {
                        t.Rows[y].Cells[x].Attributes.Add("align", "right");
                    }
                }

            }
        }

        #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);
        }
        private const string DEFAULT_TIME_SUBMIT = "Today";
        private const string DEFAULT_STATUS = "ANY";
        private const string DEFAULT_TARGET = "ANY";
        private void initSession() {
            object tmp = Request.Params["position"] != null ? Request.Params["position"] : Session[VIEWJOBS.POSITION];

            position = tmp != null ? int.Parse(tmp.ToString()) : 0;

            Session[VIEWJOBS.POSITION] = position;
            object o = Session[VIEWJOBS.TIME_SUBMIT];
            Session[VIEWJOBS.TIME_SUBMIT] = o != null ? o : DEFAULT_TIME_SUBMIT;
            o = Session[VIEWJOBS.STATUS];
            Session[VIEWJOBS.STATUS] = o != null ? o : DEFAULT_STATUS;
            o = Session[VIEWJOBS.TARGET];
            Session[VIEWJOBS.TARGET] = o != null ? o : DEFAULT_TARGET;
            o = Session[VIEWJOBS.NAME_LIKE];
            Session[VIEWJOBS.NAME_LIKE] = o != null ? o : "";
        }

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent() {
            initSession();
            this.Load += new System.EventHandler(this.Page_Load);

            WebUtils.CheckLoggedIn(Session, Response, Request);
            wsid = (long)Session["USER"];
            lmessage = Request.Params["lmessage"];
            try {
                setSize = int.Parse(Request.Params["setSize"]);
            } catch { setSize = defaultSetSize; }
            LoadMenus();
            LoadGrid(null, null);
        }
        #endregion
    }
}
