using System;
using System.Collections;
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.Servers;
using edu.jhu.Cas.Util;
using edu.jhu.Cas.Users;

namespace edu.jhu.Cas.Web {
	/// <summary>
	/// this sets up the frame and some session varaiables for the ydb screen.
	/// This appears in the left part of the frame while MYDBContent is the page on the right.
	/// </summary>
	public class MyDBIndex : System.Web.UI.Page {
		protected string lmessage=null;
		protected long wsid;
		protected bool loggedin;
		protected ArrayList publishedTables,groupTables,allTables = new ArrayList(),pendingTables,failedTables,functions,
			procedures,views;
		protected MyDBJobs jobs;
		protected TableJobs tJobs;
		protected string context,group;
        protected CasDBObjType dbobjtype;
		protected DropDownList targetDDL,groupDDL;
        protected Hashtable tinfo;
        public const string ALL_GROUPS = "All";
        public const string LOCAL_TABS = "Local Only";

		private void Page_Load(object sender, System.EventArgs e) {
            WebUtils.CheckLoggedIn(Session, Response, Request);
            try {
                wsid = (long)Session["USER"];
                if (Request.Params["maction"] != null) {
                    try {
                        switch (Request.Params["maction"]) {
                            case "d": DoDrops(Request.Params["maobjs"]); break;
                            case "p": DoDrops(Request.Params["maobjs"]); break;
                            case "u": DoDrops(Request.Params["maobjs"]); break;
                        }
                    } catch (Exception E) {
                        Response.Redirect("mydb.aspx?lmessage=" + E.Message.Replace("\n", "<br/>"));
                    }
                    return;
                }
                tJobs = new TableJobs();

                CasUsers users = new CasUsers();
                if (!users.HasMyDB(wsid)) users.CreateMyDB(wsid);
                jobs = new MyDBJobs();
                if (Request.Params["objtype"] != null)
                    dbobjtype = (CasDBObjType)Enum.Parse(typeof(CasDBObjType), Request.Params["ObjType"], true);
                else
                    dbobjtype = CasDBObjType.TABLE;

                loadDDL();
                string tmpSes = Session["CONTEXT"] as string;
                if (!Page.IsPostBack && tmpSes != null)
                    targetDDL.SelectedIndex = targetDDL.Items.IndexOf(targetDDL.Items.FindByText(tmpSes));
                context = targetDDL.SelectedItem.Text;
                loadGroupDDL();
                if (groupDDL != null && groupDDL.SelectedItem != null)
                    group = groupDDL.SelectedItem.Text;
                switch (dbobjtype) {
                    case CasDBObjType.FUNCTION:
                        functions = new ArrayList();
                        functions.AddRange(jobs.ListFunctions(wsid, context));
                        break;
                    case CasDBObjType.PROCEDURE:
                        procedures = new ArrayList();
                        procedures.AddRange(jobs.ListProcedures(wsid, context));
                        break;
                    default:
                        string[] tables = null;
                        tinfo = new Hashtable();
                        if (dbobjtype == CasDBObjType.TABLE && group != ALL_GROUPS && group != LOCAL_TABS && context.ToUpper() == "MYDB") {
                            allTables = new ArrayList();
                            groupTables = tJobs.GetGroupTablesList(wsid);
                            foreach (object o in groupTables)
                                if (o.ToString().Split('.')[0] == group)
                                    allTables.Add(o);
                        } else {
                            if (dbobjtype == CasDBObjType.VIEW) {
                                tables = jobs.Views(wsid, context);
                            } else {
                                CasTable[] cts = jobs.TableDetails(wsid, context);
                                ArrayList tmp = new ArrayList();
                                foreach (CasTable ct in cts) {
                                    tinfo.Add(ct.Name, ct);
                                    tmp.Add(ct.Name);
                                }
                                tables = (string[])tmp.ToArray(typeof(string));
                            }
                            allTables = new ArrayList();
                            if (tables != null) allTables.AddRange(tables);
                            publishedTables = tJobs.GetPublishedTablesList(wsid);
                            if (group != LOCAL_TABS)
                                groupTables = tJobs.GetGroupTablesList(wsid);
                            pendingTables = tJobs.GetPendingTablesList(wsid);
                            failedTables = tJobs.GetFailedTablesList(wsid);
                            if (context.CompareTo("MyDB") == 0 && dbobjtype == CasDBObjType.TABLE && group != LOCAL_TABS) allTables.AddRange(groupTables);
                        }
                        break;
                }
            } catch (Exception ex) {
                lmessage = ex.Message;
            }
		}
        protected void DoDrops(string list) {
            (new MyDBJobs()).DeleteTables(wsid, list, '\n');
            throw new Exception("The following table were dropped:<br/>"+list.Replace("\n","<br/>"));
        }
        protected string GetSelectionClass(CasDBObjType type) {
            if (type == dbobjtype) return "selected";
            else return "unselected";
        }
		private void loadDDL(){
			if(targetDDL.Items.Count < 2){
				Server[] targets = (new CasServers()).FindTargets(edu.jhu.Cas.Util.ID.SERVICE_ID,wsid);
				targetDDL.Items.Add("MyDB");//want mydb to be first by default
                foreach (Server s in targets) {
                    if(s.Target.ToUpper().CompareTo("MYDB") != 0)
                        targetDDL.Items.Add(s.Target);
                }
			}
		}
        private void loadGroupDDL() {
            if (context.ToUpper() != "MYDB" || dbobjtype != CasDBObjType.TABLE) return;
            if (groupDDL.Items.Count < 2) {
                CasGroups cg = new CasGroups();
                Group[] groups = cg.FindGroups(wsid, false);
                groupDDL.Items.Add(LOCAL_TABS);
                groupDDL.Items.Add(ALL_GROUPS);
                foreach (Group g in groups) {
                    groupDDL.Items.Add(g.Name);
                }
            }
        }
		
		
		protected string key= 
			"<a href=\\'#\\'>Default</a><br>"+
			"<a href=\\'#\\' class=\\'published\\'>Published</a><br>"+
			"<a href=\\'#\\' class=\\'group\\'>Group</a><br>"+
			"<a href=\\'#\\' class=\\'pending\\'>Pending</a><br>"+
			"<a href=\\'#\\' class=\\'bad_table\\'>Failed</a><br>";
		
		#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);
		}
        override protected void OnUnload(EventArgs e) {
            try {
                Session["CONTEXT"] = targetDDL.SelectedItem.Text;
            }
            catch { }
        }
	
		/// <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
	}
}