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.Users;
using edu.jhu.Cas.Util;
using edu.jhu.Cas.Web;
using edu.jhu.Cas.Servers;
using net.ivoa.VOTable;
using net.ivoa.data;
using System.Text;

namespace edu.jhu.Cas.Web {
    public class MyDBContentHelper : System.Web.UI.Page {
        protected string context, objname, objtype, action, message, mclass, columnNames, columnTypes, sampleData;
        protected long wsid;
        const string CNAME="COLUMN_NAME", CTYPE="TYPE_NAME", CSIZE="LENGTH", CPREC="PRECISION";
        static bool sstypeisfloatingpoint(string sstype) {
            switch (sstype) {
                case "real":
                case "float":
                case "double":
                case "decimal":
                    return true;
                default:
                    return false;
            }
        }
        static string sizeOrMax(int i) {
            switch(i){
                case 2147483647:
                case 2147483646:
                    return "MAX";
                default:
                    return i.ToString();
            }
        }
        protected override void OnInit(System.EventArgs ea) {
            try {
                action = Request.Params["action"];
                context = Request.Params["context"];
                objname = Request.Params["objname"];
                objtype = Request.Params["objtype"];
                wsid = long.Parse(Request.Params["wsid"]);
                DataSet ds;
                Response.ContentType = "text/xml";
                if (objname != null && objname.Split('.').Length == 3) {//ghetto group match
                    string[] tokens = objname.Split('.');
                    objname = tokens[0] + "." + tokens[1] + ".[" + tokens[2] + "]";
                }
                switch (action) {
                    case "schema":
                        try {
                            ds = (new CasJobs()).SubmitShortJob(wsid, "exec sp_columns '" + objname+"'", context, SYSTEM.TASKNAME + " SCHEMA QUERY", 0);
                        }
                        catch {
                            if (objname.Split('.').Length == 3) {//ghetto group match
                                message = "This table no longer exists and has been removed from publication.";
                                return;
                            }
                            throw;
                        }
                        StringBuilder cnames = new StringBuilder();
                        StringBuilder ctypes = new StringBuilder();
                        for (int i = 0; i < ds.Tables[0].Rows.Count; i++) {
                            if (i < ds.Tables[0].Rows.Count - 1) {
                                cnames.AppendLine(ds.Tables[0].Rows[i][CNAME] as string);
                                ctypes.AppendLine(ds.Tables[0].Rows[i][CTYPE] as string + " [" + sizeOrMax((int)ds.Tables[0].Rows[i][CSIZE]) + "]");
                            } else {
                                cnames.Append(ds.Tables[0].Rows[i][CNAME] as string);
                                ctypes.Append(ds.Tables[0].Rows[i][CTYPE] as string + " [" + sizeOrMax((int)ds.Tables[0].Rows[i][CSIZE]) + "]");
                            }
                        }
                        columnNames = cnames.ToString();
                        columnTypes = ctypes.ToString();
                        break;
                    case "sample":
                        if (objname.IndexOf(".") == -1) objname = "[" + objname + "]";
                        ds = (new CasJobs()).SubmitShortJob(wsid, "select top 100 * from " + objname, context, SYSTEM.TASKNAME + " SAMPLE QUERY", 0);
                        foreach (DataRow dr in ds.Tables[0].Rows) {
                            foreach (DataColumn dc in ds.Tables[0].Columns) {
                                if (dc.DataType == typeof(string)) {
                                    dr[dc] = HttpUtility.UrlEncode(dr[dc] as string);
                                }
                            }
                        }
                        sampleData = WrapperFactory.Wrapper2HTML(new DataSetWrapper(ds),
                            "rsttable","alt",null,null,"alt","0","0", SYSTEM.MAX_HTML_DATA_CHARS);
                        break;
                    default:
                        message = "unknown action, '"+action+"'";
                        break;
                }
            }
            catch(Exception e){
                message = HttpUtility.UrlEncode(e.Message);
            }
        }
        private string getSqlType(Type dt) {
            try {
                return VOTableUtil.GetSqlDBType(dt).ToString();
            }
            catch { return "NA"; }
        }
    }
}