using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
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 Sky.Darkness.Common.DataAccess;

public partial class Data_NavgationTree : System.Web.UI.Page
{

    public string JSON = "";

    protected void Page_Load(object sender, EventArgs e)
    {
        string method = Request.Params["cmd"].ToString().Trim();

        if ("getAllData".Equals(method))
        {
            string rootId = Request.Params["node"].ToString().Trim();
            JSON = GetAllData(rootId);
        }
        else if ("insert".Equals(method))
        {
            string parentId = Request.Params["parentId"].ToString().Trim();
            string id = Request.Params["id"].ToString().Trim();
            string title = Request.Params["text"].ToString().Trim();
            Insert(id, parentId, title);
        }
        else if ("update".Equals(method))
        {
            string id = Request.Params["id"].ToString().Trim();
            string title = Request.Params["text"].ToString().Trim();
            Update(id, title);
        }
        else if ("delete".Equals(method))
        {
            string id = Request.Params["id"].ToString().Trim();
            string parentId = Request.Params["parentId"].ToString().Trim();
            Delete(id, parentId);
        }
    }

    public string GetAllData(string rootId)
    {
        string sqlStr = "SELECT * FROM Tree WHERE parentId='" + rootId + "'";
        return SqlHelper.ExecuteSqlReader(sqlStr);
    }

    public void Insert(string id, string parentId, string title)
    {
        string sqlStr = " INSERT INTO Tree(nodeId,parentId,title) VALUES('" + id.Trim() + "','" + parentId.Trim() + "','" + title.Trim() + "')"
                      + " UPDATE Tree SET leaf=0,childCount=childCount+1 WHERE nodeId='" + parentId.Trim() + "'";
        SqlHelper.ExecuteNonQuery(sqlStr);
    }

    public void Update(string id, string title)
    {
        string sqlStr = "UPDATE Tree SET title='" + title + "' WHERE nodeId='" + id + "'";
        SqlHelper.ExecuteNonQuery(sqlStr);
    }

    public void Delete(string id, string parentId)
    {
        string sqlStr = " DELETE FROM Tree WHERE nodeId='" + id + "'" +
                        " UPDATE Tree SET childCount=childCount-1 WHERE nodeId='" + parentId.Trim() + "'" +
                        " UPDATE Tree SET leaf=1 WHERE nodeId='" + parentId.Trim() + "' AND (SELECT childCount FROM Tree WHERE nodeId='" + parentId.Trim() + "') <= 0";
        SqlHelper.ExecuteNonQuery(sqlStr);
    }
}
