using GigaTech.CMS.Web.Common.Base;
using MySql.Data.MySqlClient;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Script.Serialization;
using Newtonsoft.Json.Linq;
using GigaTech.CMS.Kernel.DataAccess;


namespace GigaTech.CMS.Web.Apps.IOTDeviceSystem
{
    /// <summary>
    /// Handler 的摘要描述
    /// </summary>
    public class Handler : HandlerBase
    {


        public override void ProcessRequest(HttpContext context)
        {
            var action = context.Request["action"];

            try
            {
                switch (action) {
                    case "test":
                        {
                            var dr = SqlHelper.ExecuteReader("Select * From iot_system_device_tree");

                            var dt = new DataTable();
                            dt.Load(dr);
                            string json = DataTableToJSONWithJavaScriptSerializer(dt);
                                context.Response.Write(json);
                      

                        }
                        break;
                    case "Learn":
                        {
                            var ip = context.Request["ip"];
                            GigaTech.CMS.Kernel.Common.Tools.SendCommandToService("Learn@" + ip);

                        }
                        break;
                    case "linkNetwork":
                        {
                            var MAC = context.Request["MAC"];
                            using (var dr = SqlHelper.ExecuteReader("Select * From iot_system_device_tree Where MAC='" + MAC + "'"))
                            {
                                if (dr.Read())
                                {
                                    string vid = dr["ID"].ToString();
                                    string vmodelid = dr["Code"].ToString();
                                    string vmodelsubid = dr["SubCode"].ToString();
                                   

                                    GigaTech.CMS.Kernel.Common.Tools.SendCommandToIOTMlinkNetwork(vid, vmodelid, vmodelsubid);
                                }
                            }
                           

                        }
                        break;
                    case "unlinkNetwork":
                        {
                            var MAC = context.Request["MAC"];
                            using (var dr = SqlHelper.ExecuteReader("Select * From iot_system_device_tree Where MAC='" + MAC + "'"))
                            {
                                if (dr.Read())
                                {
                                    string vid = dr["ID"].ToString();
                                    string vmodelid = dr["Code"].ToString();
                                    string vmodelsubid = dr["SubCode"].ToString();

                                    GigaTech.CMS.Kernel.Common.Tools.SendCommandToIOTMunlinkNetwork(vid, vmodelid, vmodelsubid);
                                }
                            }
                           

                        }
                        break;

                    case "GetIOTData":
                        {
                            var MAC = context.Request["MAC"];

                            using (var dr = SqlHelper.ExecuteReader("Select * From iot_system_device_tree Where MAC='" + MAC + "'"))
                            {
                                if (dr.Read())
                                {
                                    var jsonSerializer = new JavaScriptSerializer();
                                    context.Response.Write("{ \"success\": true,\"data\":" + jsonSerializer.Serialize((new DeviceIOTGridContent
                                    {
                                        MAC = dr["MAC"].ToString(),
                                        Code = dr["Code"].ToString(),
                                        SubCode = dr["SubCode"].ToString(),
                                        ID = dr["ID"].ToString(),
                                        IP = dr["IP"].ToString(),
                                        IpTableNote = dr["IpTableNote"].ToString(),
                                        NickName = dr["NickName"].ToString(),
                                        Model = dr["Code"].ToString() + "-" + dr["SubCode"].ToString()
                                    })) + "}");


                                }
                            }

                        }
                        break;

                    case "RemoveIOTDevice":
                        {
                            var MAC = context.Request["MAC"];

                            var sql = "Delete From iot_system_device_tree Where MAC='" + MAC + "'";
                            SqlHelper.ExecuteNonQuery(sql);

                            context.Response.Write("{\"success\":true}");
                        }
                        break;

                    case "ExecCMD":
                        {
                            var option = context.Request["option"];
                            var jsonStr = "";
                            switch (option.ToString())
                            {                               
                                case "deviceRelease":
                                    {
                                        try
                                        {
                                            GigaTech.CMS.Kernel.Common.Tools.SendCommandToIOTM(option);
                                            
                                        }
                                        catch (Exception)
                                        {
                                            context.Response.Write("{\"success\":false}");
                                        }
                                        context.Response.Write("{\"success\":true}");

                                    }
                                    break;

                            }
                           
                        }
                        break;

                    case "SaveIOTData":
                        {
                            var MAC = context.Request["MAC"];
                            var Model = context.Request["Model"];
                            var ID = context.Request["ID"];
                            var IP = context.Request["IP"];
                            var NickName = context.Request["NickName"];
                            var IpTableNote = context.Request["IpTableNote"];


                            if (MAC == "")
                            {
                                MySqlParameter[] pars = {
                                                          new MySqlParameter("@Code", Model.Split('-')[0]),
                                                          new MySqlParameter("@SubCode",  Model.Split('-')[1]),
                                                          new MySqlParameter("@ID", ID),
                                                          new MySqlParameter("@IP", IP),
                                                          new MySqlParameter("@NickName", NickName),
                                                          new MySqlParameter("@IpTableNote", IpTableNote)
                                                      };
                                SqlHelper.ExecuteNonQuery("Insert Into iot_system_device_tree (Code,SubCode,ID,IP,NickName,IpTableNote) Values(@Code,@SubCode,@ID,@IP,@NickName,@IpTableNote)", false, pars);
                            }
                            else
                            {
                                MySqlParameter[] pars = {
                                                            new MySqlParameter("@MAC", MAC),
                                                          new MySqlParameter("@ID", ID),
                                                          new MySqlParameter("@IP", IP),
                                                          new MySqlParameter("@NickName", NickName),
                                                          new MySqlParameter("@IpTableNote", IpTableNote)
                                                      };
                                SqlHelper.ExecuteNonQuery("Update iot_system_device_tree Set ID=@ID,IP=@IP,NickName=@NickName,IpTableNote=@IpTableNote Where MAC=@MAC", false, pars);
                            }
                            
                            context.Response.Write("{\"success\":true}");
                        }
                        break;
                }
            }
            catch (Exception ex)
            {

                context.Response.Write("{\"success\":false}");
            }
        }

        private class DeviceIOTGridContent
        {
            public string MAC;
            public string Code;
            public string SubCode;
            public string ID;
            public string SubID;
            public string IP;
            public string SubMask;
            public string IpTableNote;
            public string NickName;
            public string Model;
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }

        public string DataTableToJSONWithJavaScriptSerializer(DataTable table)
        {
            JavaScriptSerializer jsSerializer = new JavaScriptSerializer();
            List<Dictionary<string, object>> parentRow = new List<Dictionary<string, object>>();
            Dictionary<string, object> childRow;
            foreach (DataRow row in table.Rows)
            {
                childRow = new Dictionary<string, object>();
                foreach (DataColumn col in table.Columns)
                {
                    childRow.Add(col.ColumnName, row[col].ToString());
                }
                parentRow.Add(childRow);
            }
            return jsSerializer.Serialize(parentRow);
        }

    }
}