using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.IO;
using DSWeb.Models;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;

namespace DSWeb.UserSettings
{
    public partial class GridEdit : System.Web.UI.Page
    {
        private string strUserID;
        private string strHandle;
        private string strTemplateName;

        protected void Page_Load(object sender, EventArgs e)
        {
            if (Session["USERID"] != null)
            {
                strUserID = Session["USERID"].ToString();
                h_userid.Value = strUserID;
            }

            if (Request.QueryString["handle"] != null)
            {
                strHandle = Request.QueryString["handle"].ToString().Trim().ToLower();
            }

            if (Request.QueryString["templatename"] != null)
            {
                strTemplateName = Request.QueryString["templatename"].ToString().Trim().ToLower();
                h_templatename.Value = strTemplateName;
            }

            if (strHandle == "usergrid")
            {
                this.btn_new.Visible = false;
                this.sel_gtype.Disabled = true;
            }

            if (strHandle == "template")
            {
                this.btn_new.Visible = true;
                this.sel_gtype.Disabled = false;
            }
            //if (this.Page.Header.FindControl("script") != null)
            //{
            //    int iCount = 0;
            //    foreach (HtmlGenericControl objInclude in this.Page.Header.Controls)
            //    {
            //        if (objInclude.Attributes["id"].ToString().Equals("opseae"))
            //        {
            //            this.Page.Header.Controls.Remove(objInclude);
            //            HtmlGenericControl Include = new HtmlGenericControl("script");
            //            Include.Attributes.Add("id", "opseae");
            //            Include.Attributes.Add("type", "text/javascript");
            //            Include.Attributes.Add("charset", "gb2312");
            //            Include.Attributes.Add("src", "UserGridSource/TemplateOpseaeGrid.js");
            //            this.Page.Header.Controls.Add(Include);

            //            iCount++;
            //            break;
            //        }
            //    }

            //    if(iCount == 0)
            //    {
            //        HtmlGenericControl Include = new HtmlGenericControl("script");
            //        Include.Attributes.Add("id", "opseae");
            //        Include.Attributes.Add("type", "text/javascript");
            //        Include.Attributes.Add("charset", "gb2312");
            //        Include.Attributes.Add("src", "UserGridSource/TemplateOpseaeGrid.js");
            //        Include.Attributes.Add("src", "UserGridSource/TemplateOpseaeGrid.js");
            //        this.Page.Header.Controls.Add(Include);
            //    }
            //}
            //else
            //{
            //    HtmlGenericControl Include = new HtmlGenericControl("script");
            //    Include.Attributes.Add("id", "opseae");
            //    Include.Attributes.Add("type", "text/javascript");
            //    Include.Attributes.Add("charset", "gb2312");
            //    Include.Attributes.Add("src", "UserGridSource/TemplateOpseaeGrid.js");
            //    this.Page.Header.Controls.Add(Include);
            //}
            HtmlGenericControl Include = new HtmlGenericControl("script");
            Include.Attributes.Add("id", strTemplateName);
            Include.Attributes.Add("type", "text/javascript");
            Include.Attributes.Add("charset", "gb2312");
            Include.Attributes.Add("src", "UserGridSource/Template" + strTemplateName + "Grid.js");
            this.Page.Header.Controls.Add(Include);
        }

        protected void btn_save_Click(object sender, EventArgs e)
        {
            if (strHandle == "usergrid" && strTemplateName != null)
            {
                if (h_gridcache.Value.Trim() != "")
                {
                    StringBuilder headerBuilder = new StringBuilder();
                    StringBuilder widthBuilder = new StringBuilder();
                    StringBuilder colAlignBuilder = new StringBuilder();
                    StringBuilder colSortBuilder = new StringBuilder();
                    StringBuilder colTypeBuilder = new StringBuilder();

                    string gridInfo = "";
                    string gridCache = h_gridcache.Value.Trim();
                    gridInfo = gridCache.Substring(gridCache.IndexOf("[") + 1, gridCache.IndexOf("]") - gridCache.IndexOf("[") - 1);

                    IList<TemplateGridEntity> templateGridEntities = new List<TemplateGridEntity>();

                    string[] items = gridInfo.Split(new string[] { "},{" }, System.StringSplitOptions.RemoveEmptyEntries);

                    if (items.Length > 0)
                    {
                        for (int i = 0; i < items.Length; i++)
                        {
                            items[i] = items[i].ToString().Replace("{", "");
                            items[i] = items[i].ToString().Replace("}", "");
                            string[] strCell = items[i].Split(new char[] { ',' });

                            if (strCell.Length > 0)
                            {
                                TemplateGridEntity templateGridEntity = new TemplateGridEntity();

                                for (int j = 0; j < strCell.Length; j++)
                                {
                                    string[] strArg = strCell[j].Split(new char[] { ':' });

                                    switch (strArg[0].Replace("\"", ""))
                                    {
                                        case "title":
                                            templateGridEntity.Title = UnicodeToGB(strArg[1].ToString().Replace("\"", "").Trim());
                                            break;
                                        case "name":
                                            templateGridEntity.Name = strArg[1].ToString().Replace("\"", "").Trim();
                                            break;
                                        case "index":
                                            templateGridEntity.Index = int.Parse(strArg[1].ToString().Replace("\"", "").Trim());
                                            break;
                                        case "type":
                                            templateGridEntity.Type = strArg[1].ToString().Replace("\"", "").Trim();
                                            break;
                                        case "width":
                                            templateGridEntity.Width = int.Parse(strArg[1].ToString().Replace("\"", "").Trim());
                                            break;
                                        case "sort":
                                            templateGridEntity.Sort = strArg[1].ToString().Replace("\"", "").Trim();
                                            break;
                                        case "remark":
                                            templateGridEntity.Remark = strArg[1].ToString().Replace("\"", "").Trim();
                                            break;
                                        case "gtype":
                                            templateGridEntity.GType = strArg[1].ToString().Replace("\"", "").Trim();
                                            break;
                                        case "align":
                                            templateGridEntity.Align = strArg[1].ToString().Replace("\"", "").Trim();
                                            break;
                                        case "pk":
                                            templateGridEntity.PK = int.Parse(strArg[1].ToString().Replace("\"", "").Trim());
                                            break;
                                        case "close":
                                            templateGridEntity.Closed = int.Parse(strArg[1].ToString().Replace("\"", "").Trim());
                                            break;
                                        default:
                                            break;
                                    }
                                }

                                templateGridEntities.Add(templateGridEntity);
                            }
                        }

                        headerBuilder.Append("var newHeaderArgs = new Array(");
                        widthBuilder.Append("var newWidthArgs = new Array(");
                        colAlignBuilder.Append("var newColAlignArgs = new Array(");
                        colSortBuilder.Append("var newColSortArgs = new Array(");
                        colTypeBuilder.Append("var newColTypeArgs = new Array(");

                        int iCount = 0;
                        for (int j = 0; j < templateGridEntities.Count; j++)
                        {
                            if (templateGridEntities[j].PK == 0 && templateGridEntities[j].Closed == 0)
                            {
                                if (j == (templateGridEntities.Count - 1))
                                {
                                    headerBuilder.Append("\"" + templateGridEntities[j].Title + "\"");
                                    widthBuilder.Append("\"" + templateGridEntities[j].Width + "\"");
                                    colAlignBuilder.Append("\"" + templateGridEntities[j].Align + "\"");
                                    colSortBuilder.Append("\"" + templateGridEntities[j].Name + "\"");
                                    colTypeBuilder.Append("\"" + templateGridEntities[j].GType + "\"");
                                    iCount++;
                                }
                                else
                                {
                                    headerBuilder.Append("\"" + templateGridEntities[j].Title + "\",");
                                    widthBuilder.Append("\"" + templateGridEntities[j].Width + "\",");
                                    colAlignBuilder.Append("\"" + templateGridEntities[j].Align + "\",");
                                    colSortBuilder.Append("\"" + templateGridEntities[j].Name + "\",");
                                    colTypeBuilder.Append("\"" + templateGridEntities[j].GType + "\",");
                                    iCount++;
                                }
                            }
                        }
                        string headerResult = headerBuilder.ToString().Trim();
                        string widthResult = widthBuilder.ToString().Trim();
                        string colAlignResult = colAlignBuilder.ToString().Trim();
                        string colSortResult = colSortBuilder.ToString().Trim();
                        string colTypeResult = colTypeBuilder.ToString().Trim();
                        
                        headerResult = (headerResult.EndsWith(",") ? headerResult.Substring(0, headerResult.Length - 1) : headerResult) + ");";
                        widthResult = (widthResult.EndsWith(",") ? widthResult.Substring(0, widthBuilder.Length - 1) : widthResult) + ");";
                        colAlignResult = (colAlignResult.EndsWith(",") ? colAlignResult.Substring(0, colAlignResult.Length - 1) : colAlignResult) + ");";
                        colSortResult = (colSortResult.EndsWith(",") ? colSortResult.Substring(0, colSortResult.Length - 1) : colSortResult) + ");";
                        colTypeResult = (colTypeResult.EndsWith(",") ? colTypeResult.Substring(0, colTypeResult.Length - 1) : colTypeResult) + ");";
                        

                        if (iCount > 0)
                        {
                            string result = headerResult + widthResult + colAlignResult + colSortResult + colTypeResult;
                            WriteUserGridSource(strUserID, "UserGridSource", "grid" + strTemplateName + ".js", result);
                        }
                    }
                }

                
                
            }
            
        }

        private int ReadUserGridSource(string tempUserID,string tempUrl,GridType tempGridType)
        {
            int iResult = 0;
            return iResult;
        }

        private int WriteUserGridSource(string tempUserID, string tempUrl, string tempFileName,string tempWriteContent)
        {
            int iResult = 0;

            try
            {
                string filePath = Server.MapPath(tempUrl);

                if (!Directory.Exists(filePath))
                {
                    // Create the directory it does not exist.
                    Directory.CreateDirectory(filePath);
                }

                string targetUrl = @"" + filePath + "\\" + strUserID + tempFileName;
                FileInfo fileInfo = new FileInfo(targetUrl);

                if (fileInfo.Exists)
                {
                    //fileInfo.Delete();
                    //FileInfo fi = new FileInfo(targetUrl);

                    //fi.Create();
                    FileStream fs = fileInfo.Create();

                    StreamWriter swFromFileStream = new StreamWriter(fs);
                    swFromFileStream.Write(tempWriteContent);
                    swFromFileStream.Flush();
                    swFromFileStream.Close();

                    fs.Close();
                }
                else
                {
                    //FileInfo fi = new FileInfo(targetUrl);
                    FileStream fs = fileInfo.Create();

                    StreamWriter swFromFileStream = new StreamWriter(fs);
                    swFromFileStream.Write(tempWriteContent);
                    swFromFileStream.Flush();
                    swFromFileStream.Close();

                    fs.Close();
                    //fileInfo.Delete();
                }
            }
            catch (Exception)
            {
            }
            return iResult;
        }

        private string CreateGridItemConfig()
        {
            string strResult = "";
            return strResult;
        }

        private void initGridType()
        {            
        }

        public string UnicodeToGB(string text)
        {
            MatchCollection mc = Regex.Matches(text, "([\\w]+)|(\\\\u([\\w]{4}))");
            if (mc != null && mc.Count > 0)
            {
                StringBuilder sb = new StringBuilder();
                foreach (Match m2 in mc)
                {
                    string v = m2.Value;
                    if (v.IndexOf("\\") >= 0)
                    {
                        string word = v.Substring(2);
                        byte[] codes = new byte[2];
                        int code = Convert.ToInt32(word.Substring(0, 2), 16);
                        int code2 = Convert.ToInt32(word.Substring(2), 16);
                        codes[0] = (byte)code2;
                        codes[1] = (byte)code;
                        sb.Append(Encoding.Unicode.GetString(codes));
                    }
                    else
                    {
                        sb.Append(v);
                    }
                }
                return sb.ToString();
            }
            else
            {
                return text;
            }
        }

        private string GetOrigGridInfo()
        {
            string strResult = "";
            if (h_origcache.Value.Trim() != "")
            {
                StringBuilder headerBuilder = new StringBuilder();
                StringBuilder widthBuilder = new StringBuilder();
                StringBuilder colAlignBuilder = new StringBuilder();
                StringBuilder colSortBuilder = new StringBuilder();
                StringBuilder colTypeBuilder = new StringBuilder();

                string gridInfo = "";
                string gridCache = h_origcache.Value.Trim();
                gridInfo = gridCache.Substring(gridCache.IndexOf("[") + 1, gridCache.IndexOf("]") - gridCache.IndexOf("[") - 1);

                IList<TemplateGridEntity> templateGridEntities = new List<TemplateGridEntity>();

                string[] items = gridInfo.Split(new string[] { "},{" }, System.StringSplitOptions.RemoveEmptyEntries);

                if (items.Length > 0)
                {
                    for (int i = 0; i < items.Length; i++)
                    {
                        items[i] = items[i].ToString().Replace("{", "");
                        items[i] = items[i].ToString().Replace("}", "");
                        string[] strCell = items[i].Split(new char[] { ',' });

                        if (strCell.Length > 0)
                        {
                            TemplateGridEntity templateGridEntity = new TemplateGridEntity();

                            for (int j = 0; j < strCell.Length; j++)
                            {
                                string[] strArg = strCell[j].Split(new char[] { ':' });

                                switch (strArg[0].Replace("\"", ""))
                                {
                                    case "title":
                                        templateGridEntity.Title = UnicodeToGB(strArg[1].ToString().Replace("\"", "").Trim());
                                        break;
                                    case "name":
                                        templateGridEntity.Name = strArg[1].ToString().Replace("\"", "").Trim();
                                        break;
                                    case "index":
                                        templateGridEntity.Index = int.Parse(strArg[1].ToString().Replace("\"", "").Trim());
                                        break;
                                    case "type":
                                        templateGridEntity.Type = strArg[1].ToString().Replace("\"", "").Trim();
                                        break;
                                    case "width":
                                        templateGridEntity.Width = int.Parse(strArg[1].ToString().Replace("\"", "").Trim());
                                        break;
                                    case "sort":
                                        templateGridEntity.Sort = strArg[1].ToString().Replace("\"", "").Trim();
                                        break;
                                    case "remark":
                                        templateGridEntity.Remark = strArg[1].ToString().Replace("\"", "").Trim();
                                        break;
                                    case "gtype":
                                        templateGridEntity.GType = strArg[1].ToString().Replace("\"", "").Trim();
                                        break;
                                    case "align":
                                        templateGridEntity.Align = strArg[1].ToString().Replace("\"", "").Trim();
                                        break;
                                    case "pk":
                                        templateGridEntity.PK = int.Parse(strArg[1].ToString().Replace("\"", "").Trim());
                                        break;
                                    case "close":
                                        templateGridEntity.Closed = int.Parse(strArg[1].ToString().Replace("\"", "").Trim());
                                        break;
                                    default:
                                        break;
                                }
                            }

                            templateGridEntities.Add(templateGridEntity);
                        }
                    }
                    headerBuilder.Append("var headerArgs_orderlist = new Array(");
                    widthBuilder.Append("var widthArgs_orderlist = new Array(");
                    colAlignBuilder.Append("var colAlignArgs_orderlist = new Array(");
                    colSortBuilder.Append("var colSortArgs_orderlist = new Array(");
                    colTypeBuilder.Append("var colTypeArgs_orderlist = new Array(");

                    int iCount = 0;
                    for (int j = 0; j < templateGridEntities.Count; j++)
                    {
                        if (templateGridEntities[j].PK == 0 && templateGridEntities[j].Closed == 0)
                        {
                            if (j == (templateGridEntities.Count - 1))
                            {
                                headerBuilder.Append("\"" + templateGridEntities[j].Title + "\"");
                                widthBuilder.Append("\"" + templateGridEntities[j].Width + "\"");
                                colAlignBuilder.Append("\"" + templateGridEntities[j].Align + "\"");
                                colSortBuilder.Append("\"" + templateGridEntities[j].Name + "\"");
                                colTypeBuilder.Append("\"" + templateGridEntities[j].GType + "\"");
                                iCount++;
                            }
                            else
                            {
                                headerBuilder.Append("\"" + templateGridEntities[j].Title + "\",");
                                widthBuilder.Append("\"" + templateGridEntities[j].Width + "\",");
                                colAlignBuilder.Append("\"" + templateGridEntities[j].Align + "\",");
                                colSortBuilder.Append("\"" + templateGridEntities[j].Name + "\",");
                                colTypeBuilder.Append("\"" + templateGridEntities[j].GType + "\",");
                                iCount++;
                            }
                        }
                    }
                    string headerResult = headerBuilder.ToString().Trim();
                    string widthResult = widthBuilder.ToString().Trim();
                    string colAlignResult = colAlignBuilder.ToString().Trim();
                    string colSortResult = colSortBuilder.ToString().Trim();
                    string colTypeResult = colTypeBuilder.ToString().Trim();

                    headerResult = (headerResult.EndsWith(",") ? headerResult.Substring(0, headerResult.Length - 1) : headerResult) + ");";
                    widthResult = (widthResult.EndsWith(",") ? widthResult.Substring(0, widthBuilder.Length - 1) : widthResult) + ");";
                    colAlignResult = (colAlignResult.EndsWith(",") ? colAlignResult.Substring(0, colAlignResult.Length - 1) : colAlignResult) + ");";
                    colSortResult = (colSortResult.EndsWith(",") ? colSortResult.Substring(0, colSortResult.Length - 1) : colSortResult) + ");";
                    colTypeResult = (colTypeResult.EndsWith(",") ? colTypeResult.Substring(0, colTypeResult.Length - 1) : colTypeResult) + ");";


                    if (iCount > 0)
                    {
                        strResult = headerResult + widthResult + colAlignResult + colSortResult + colTypeResult;
                    }
                }
            }

            return strResult;
        }
    }

    public enum GridType
    {
        OPSEAE = 1,
        FEEEDIT = 2
    }
}