using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Dynamic;
using System.Web;
using System.Web.Mvc;
using Service;
using Domain;
using Newtonsoft.Json;

namespace WebSite.Controllers
{
    public class SearchHostController : BaseController
    {
        public ISearchHostManager SearchHostManager { get; set; }

        public IHostManager HostManager { get; set; }

        public IGroupManager GroupManager { get; set; }

        public IRoomTypeManager RoomTypeManager { get; set; }
        
        public ActionResult Index()
        {
            return View();
        }

        [Authorize]
        public ActionResult RegisterHost(string hostNumber, string ip, string subnetmask, string gateway, int port, string mac, string version, string configVersion)
        {
            var host = HostManager.GetByMAC(mac, CurrentHotelID);
            if (host != null)
            {
                host.HostNumber = hostNumber;
                host.IP = ip;
                host.SubnetMask = subnetmask;
                host.Gateway = gateway;
                host.Port = port;
                host.Version = version;
                host.ConfigVersion = configVersion;

                return View(host);
            }

            return View(new Host
            {
                ID = 0,
                HostNumber = hostNumber,
                Version = version,
                ConfigVersion = configVersion,
                RoomNumber = hostNumber,
                IP = ip,
                SubnetMask = subnetmask,
                Gateway = gateway,
                Port = port,
                MAC = mac,
                Group = null,
                Remark = ""
            });
        }

        public ActionResult RegisterHosts(string hosts, int groupId, int roomTypeId)
        {
            try
            {
                var group = GroupManager.Get(groupId);
                if (group == null)
                {
                    throw new ApplicationException(HttpContext.InnerLanguage("InvalidFloor"));
                }

                var roomType = RoomTypeManager.Get(roomTypeId);
                if (roomType == null)
                {
                    throw new ApplicationException(HttpContext.InnerLanguage("InvalidRoomType"));
                }

                var hostList = JsonConvert.DeserializeObject<List<SearchHost>>(hosts);
                if (hostList == null || hostList.Count == 0)
                {
                    throw new ApplicationException(HttpContext.InnerLanguage("PleaseSelectRegisteredHost"));
                }

                foreach (var host in hostList)
                {
                    if (host.Registered)
                    {
                        var entity = HostManager.GetByMAC(host.MAC, CurrentHotelID);

                        entity.Group = group;
                        entity.RoomType = roomType;
                        entity.IP = host.IP;
                        entity.SubnetMask = host.SubnetMask;
                        entity.Gateway = host.Gateway;
                        entity.Port = host.Port;
                        entity.HostNumber = host.HostNumber;
                        entity.Version = host.Version;
                        entity.ConfigVersion = host.ConfigVersion;

                        HostManager.Update(entity);
                    }
                    else
                    {
                        var entity = new Host();

                        entity.Group = group;
                        entity.RoomType = roomType;
                        entity.MAC = host.MAC;
                        entity.IP = host.IP;
                        entity.SubnetMask = host.SubnetMask;
                        entity.Gateway = host.Gateway;
                        entity.Port = host.Port;
                        entity.HostNumber = host.HostNumber;
                        entity.RoomNumber = host.HostNumber;
                        entity.Version = host.Version;
                        entity.ConfigVersion = host.ConfigVersion;

                        HostManager.Save(entity);
                    }
                }

                return Json(new { IsSuccess = true, Message = HttpContext.InnerLanguage("RegisterSuccess") });
            }
            catch (Exception ex)
            {
                return Json(new { IsSuccess = false, Message = HttpContext.InnerLanguage("RegisterFailedBecause") + ex.Message });
            }
        }

        [Authorize]
        [HttpPost]
        public ActionResult StartSearch(int registered)
        {
            try
            {
                if (!String.IsNullOrEmpty(SearchHostManager.User))
                {
                    throw new ApplicationException(HttpContext.InnerLanguage("User") + "【" + SearchHostManager.User + "】" + HttpContext.InnerLanguage("SearchingForAHostTheSameTimeThereCanBeOnlyOneUserSearchHost"));
                }

                IList<SearchHost> hostList = Session["HostList"] as IList<SearchHost>;
                if (hostList == null)
                {
                    hostList = new List<SearchHost>();
                }
                SearchHostManager.Start(delegate(SearchHost host)
                {
                    if (hostList == null)
                    {
                        SearchHostManager.Stop();
                    }
                    //如果存在缓存中，则不再添加
                    SearchHost msg = hostList.FirstOrDefault(r => r.MAC == host.MAC);
                    if (msg == null)
                    {
                        if (SearchHostManager.UpdateHost(host, CurrentHotelID))//如已注册，则更新子网掩码等信息
                        {
                            host.Registered = true;
                        }
                        else
                        {
                            host.Registered = false;
                        }
                        if (registered == 0 ||
                            (registered == 1 && host.Registered) ||
                            (registered == 2 && !host.Registered))
                        {
                            hostList.Add(host);
                        }
                    }
                });
                Session["HostList"] = hostList;
                SearchHostManager.User = User.Identity.Name;

                return Json(new { IsSuccess = true });
            }
            catch (ApplicationException ex)
            {
                return Json(new { IsSuccess = false, Message = ex.Message });
            }
        }


        [Authorize]
        [HttpPost]
        public ActionResult ClearSearchResult()
        {
			IList<SearchHost> hostList = Session["HostList"] as IList<SearchHost>;
			if (hostList != null)
			{
				hostList.Clear();
			}

			return Json(new { IsSuccess = true });
        }


        [Authorize]
        [HttpPost]
        public ActionResult GetSearchResult(int page, int rows, string order, string sort)
        {
            SearchHostManager.Start();

            var list = Session["HostList"] as IList<SearchHost>;
            //var list = MockHosts();

            if (list == null)
            {
                list = new List<SearchHost>();
            }
            var result = list.AsQueryable().OrderBy(sort + " " + order).Skip((page - 1) * rows).Take(rows);

            return Json(new { IsSuccess = true, Data = new { total = list.Count(), rows = result } });
            //return Json(new { IsSuccess = false });
        }

        [Authorize]
        public ActionResult Searching()
        {
            if (SearchHostManager.User == this.User.Identity.Name)
            {
                return Json(new { IsSuccess = true, searching = SearchHostManager.Searching });
            }

            return Json(new { IsSuccess = true, searching = false });
        }

        [Authorize]
        [HttpPost]
        public ActionResult StopSearch()
        {
            SearchHostManager.Stop();

            return Json(new { IsSuccess = true, Message = HttpContext.InnerLanguage("StoppedSearching") });
        }

#if DEBUG
        private IList<SearchHost> MockHosts()
        {
            var hosts = new List<SearchHost>();

            hosts.Add(new SearchHost { Registered = true, IP = "192.168.1.111", HostNumber = "101", SubnetMask = "255.255.255.0", Gateway = "192.168.1.1", Port = 3341, MAC = "D0-50-99-56-51-51", Version = "1.0.1", ConfigVersion = "1.1.000" });
            hosts.Add(new SearchHost { Registered = true, IP = "192.168.1.112", HostNumber = "102", SubnetMask = "255.255.255.0", Gateway = "192.168.1.1", Port = 3341, MAC = "D0-50-99-56-51-52", Version = "1.0.2", ConfigVersion = "1.1.000" });
            hosts.Add(new SearchHost { Registered = true, IP = "192.168.1.113", HostNumber = "103", SubnetMask = "255.255.255.0", Gateway = "192.168.1.1", Port = 3341, MAC = "D0-50-99-56-51-53", Version = "1.0.3", ConfigVersion = "1.1.000" });
            hosts.Add(new SearchHost { Registered = true, IP = "192.168.1.114", HostNumber = "104", SubnetMask = "255.255.255.0", Gateway = "192.168.1.1", Port = 3341, MAC = "D0-50-99-56-51-54", Version = "1.0.4", ConfigVersion = "1.1.000" });
            hosts.Add(new SearchHost { Registered = true, IP = "192.168.1.115", HostNumber = "105", SubnetMask = "255.255.255.0", Gateway = "192.168.1.1", Port = 3341, MAC = "D0-50-99-56-51-55", Version = "1.0.5", ConfigVersion = "1.1.000" });
            hosts.Add(new SearchHost { Registered = true, IP = "192.168.1.116", HostNumber = "106", SubnetMask = "255.255.255.0", Gateway = "192.168.1.1", Port = 3341, MAC = "D0-50-99-56-51-56", Version = "1.0.6", ConfigVersion = "1.1.000" });
            hosts.Add(new SearchHost { Registered = true, IP = "192.168.1.117", HostNumber = "107", SubnetMask = "255.255.255.0", Gateway = "192.168.1.1", Port = 3341, MAC = "D0-50-99-56-51-57", Version = "1.0.7", ConfigVersion = "1.1.000" });
            hosts.Add(new SearchHost { Registered = true, IP = "192.168.1.118", HostNumber = "108", SubnetMask = "255.255.255.0", Gateway = "192.168.1.1", Port = 3341, MAC = "D0-50-99-56-51-58", Version = "1.0.8", ConfigVersion = "1.1.000" });
            hosts.Add(new SearchHost { Registered = true, IP = "192.168.1.119", HostNumber = "109", SubnetMask = "255.255.255.0", Gateway = "192.168.1.1", Port = 3341, MAC = "D0-50-99-56-51-59", Version = "1.0.9", ConfigVersion = "1.1.000" });
            hosts.Add(new SearchHost { Registered = true, IP = "192.168.1.120", HostNumber = "110", SubnetMask = "255.255.255.0", Gateway = "192.168.1.1", Port = 3341, MAC = "D0-50-99-56-51-60", Version = "1.0.10", ConfigVersion = "1.1.000" });
            hosts.Add(new SearchHost { Registered = true, IP = "192.168.1.121", HostNumber = "111", SubnetMask = "255.255.255.0", Gateway = "192.168.1.1", Port = 3341, MAC = "D0-50-99-56-51-61", Version = "1.0.1", ConfigVersion = "1.1.000" });
            hosts.Add(new SearchHost { Registered = true, IP = "192.168.1.122", HostNumber = "112", SubnetMask = "255.255.255.0", Gateway = "192.168.1.1", Port = 3341, MAC = "D0-50-99-56-51-62", Version = "1.0.2", ConfigVersion = "1.1.000" });
            hosts.Add(new SearchHost { Registered = true, IP = "192.168.1.123", HostNumber = "113", SubnetMask = "255.255.255.0", Gateway = "192.168.1.1", Port = 3341, MAC = "D0-50-99-56-51-63", Version = "1.0.3", ConfigVersion = "1.1.000" });
            hosts.Add(new SearchHost { Registered = true, IP = "192.168.1.124", HostNumber = "114", SubnetMask = "255.255.255.0", Gateway = "192.168.1.1", Port = 3341, MAC = "D0-50-99-56-51-64", Version = "1.0.4", ConfigVersion = "1.1.000" });
            hosts.Add(new SearchHost { Registered = true, IP = "192.168.1.125", HostNumber = "115", SubnetMask = "255.255.255.0", Gateway = "192.168.1.1", Port = 3341, MAC = "D0-50-99-56-51-65", Version = "1.0.5", ConfigVersion = "1.1.000" });
            hosts.Add(new SearchHost { Registered = true, IP = "192.168.1.126", HostNumber = "116", SubnetMask = "255.255.255.0", Gateway = "192.168.1.1", Port = 3341, MAC = "D0-50-99-56-51-66", Version = "1.0.6", ConfigVersion = "1.1.000" });
            hosts.Add(new SearchHost { Registered = true, IP = "192.168.1.127", HostNumber = "117", SubnetMask = "255.255.255.0", Gateway = "192.168.1.1", Port = 3341, MAC = "D0-50-99-56-51-67", Version = "1.0.7", ConfigVersion = "1.1.000" });
            hosts.Add(new SearchHost { Registered = true, IP = "192.168.1.128", HostNumber = "118", SubnetMask = "255.255.255.0", Gateway = "192.168.1.1", Port = 3341, MAC = "D0-50-99-56-51-68", Version = "1.0.8", ConfigVersion = "1.1.000" });
            hosts.Add(new SearchHost { Registered = true, IP = "192.168.1.129", HostNumber = "119", SubnetMask = "255.255.255.0", Gateway = "192.168.1.1", Port = 3341, MAC = "D0-50-99-56-51-69", Version = "1.0.9", ConfigVersion = "1.1.000" });
            hosts.Add(new SearchHost { Registered = true, IP = "192.168.1.130", HostNumber = "120", SubnetMask = "255.255.255.0", Gateway = "192.168.1.1", Port = 3341, MAC = "D0-50-99-56-51-70", Version = "1.0.10", ConfigVersion = "1.1.000" });

            return hosts;
        }
#endif	//#if DEBUG
    }
}
