using System;
using System.Collections;
using System.Collections.Specialized;
using System.Data;
using System.IO;
using System.Data.SqlClient;

using ms.aq.cview.query;
using ms.aq.cview.util;
using ms.aq.cview.draw;

namespace ms.aq.cview {
    public class NoValuesFound : Exception { }
    public class preview : System.Web.UI.Page {
        public const string BASETABLE = "BASETABLE";

        protected string dataQ = "No query available";
        protected string error = null;
        protected int status = 0, block_size;
        protected string tokens;
        protected int width, height;
        protected bool canPlot;

        const int top_m = 25,
                right_m = 25,
                bottom_m = 60,
                left_m = 80;
        protected DBNumber xmin, xmax, xdif, ymin, ymax, ydif;
        protected Serie[] Legend;
        /*
         * some browers will insist on the plot picture.
         * ssid is a garbage param append to img.aspx (img.aspx?garbage)
         * it should be unique for each possible img.
         */
        protected string ssid = "";

        override protected void OnInit(EventArgs e) {
            InitializeComponent();
            base.OnInit(e);
        }

        private SelectionSets getSelectionSets(string ptype, string prefix, string val, string rval, string agg) {
            SelectionSets ss = Session[Settings.SESSION_SS_KEY] != null ?
                        (SelectionSets)Session[Settings.SESSION_SS_KEY] : new SelectionSets();
            ss.Agg = common.StringToAgg(agg);
            ss.PlotType = ptype;

            //can process both an add and remove for the same prefix
            if (rval != null && rval != "")//remove                
                ss.RemoveSelection(prefix, rval);
            if (val != null && val != "")//add
                ss.AddSelection(prefix, val);
            Session[Settings.SESSION_SS_KEY] = ss;
            return ss;
        }

        private void storeTableInfo(IDataReader reader, string intoTable) {
            ClotTable ct = new ClotTable();
            ct.TableName = intoTable;
            for (int i = 0; i < reader.FieldCount; i++)
                if (reader.GetName(i).StartsWith(Settings.XDIM_PREF))
                    ct.XCols.Add(reader.GetName(i));
                else
                    ct.YCols.Add(reader.GetName(i));
            Session[BASETABLE] = ct;
        }

        private void InitializeComponent() {
            try {
                Response.ContentType = "text/xml";
                string ptype = Request.Params["ptype"];
                string prefix = Request.Params["targ"];
                string reset = Request.Params["reset"];                   
                long wsid = (long)Session["USER"];
                if (reset != null && reset == "true") {
                    Session[Settings.SESSION_SS_KEY] = null;
                    return;
                }
                status = 0;
                if (ptype == null) {
                    return;//nothing clicked, just the page loading
                }
                SelectionSets ss = getSelectionSets(ptype, prefix, Request.Params["val"], Request.Params["rval"], Request.Params["agg"]);
                ssid = ss.ComputeIdentifier();
                status = 1;               
                if (Request.Params["doplot"] == null || Request.Params["doplot"] != "true") return;
                block_size = int.Parse(Request.Params["rez"]);
                width = Request.Params["width"] != null ? int.Parse(Request.Params["width"].ToString()) : 320;
                height = Request.Params["height"] != null ? int.Parse(Request.Params["height"].ToString()) : 200;
                
                
                //new query, do the whole thing
                table_cube_interface tci = new table_cube_interface(wsid);
                tci.TableName = Session[BASETABLE] as string;
                table_query_monkey tqm = new table_query_monkey(tci);

                string minMaxQ = tqm.BuildMinMax(ref ss);
                DateTime start = DateTime.Now;
                DataSet minMax = tci.ExecuteQuery(minMaxQ);//grab limits                                        
                double eTime = (DateTime.Now - start).TotalSeconds;
                MemoryStream ms = new MemoryStream();
                int points = -1;
                double rTime = -1;
                start = DateTime.Now;
                Clotter clotter = new Clotter(minMax, ss, width, height, top_m,
                    right_m, bottom_m, left_m, 15, 10, 5, 5, block_size);
                string dataQ = tqm.BuildDataQuery(ref ss, width - left_m - right_m, height - top_m - bottom_m, 
                    clotter.XMin, clotter.XMax, clotter.XDif, clotter.YMin, clotter.YMax, clotter.YDif, block_size);
                
                DataSet ds = tci.ExecuteQuery(dataQ);
                clotter.DrawPoints(ds, out Legend);
                clotter.Save(ms);
                rTime = (DateTime.Now - start).TotalSeconds;

                ms.Position = 0;
                Session["ISTREAM"] = ms;

                tokens = PInfoFactory.SS2HTML(tci, ss, Legend, points, eTime, rTime, out canPlot);
                status = 2;
            }
            catch (Exception e) {
                error = "<pre>" + e.Message + "</pre>";
                status = 3;
            }
        }
    }
}
