using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Domain;
using Service;

namespace WebSite.Controllers
{
    public class LightControlController : BaseController
	{
		private const int AUTHORITY_LightControl = 13;

		public ILightControlManager LightControlManager { get; set; }

		public IHostManager HostManager { get; set; }

		public IHostModalManager HostModalManager { get; set; }

		public IGroupManager GroupManager { get; set; }

		public IRoomStatusManager RoomStatusManager { get; set; }

		public IRoomTypeManager RoomTypeManager { get; set; }

		public IRoomTypeSceneManager RoomTypeSceneManager { get; set; }

		#region Actions

		[Authorize]
        public ActionResult Index()
        {
			return View("SimonIndex");
		}

		[Authorize]
        public ActionResult SendScene(string jsonScene, int? hostID, int? groupID, int? roomStatusID, int? roomTypeID, bool? takeInverse)
		{
			try
			{
                IList<string> roomNumberList = new List<string>();
				var hostList = FindHosts(hostID, groupID, roomStatusID, roomTypeID);
				var sceneSetting = Newtonsoft.Json.JsonConvert.DeserializeObject<LightSceneSetting>(jsonScene);
				if (sceneSetting == null)
				{
					return Json(new { IsSuccess = false, Message = HttpContext.InnerLanguage("InvalidScene") });
				}
				var scene = RoomTypeSceneManager.Get(sceneSetting.SceneID);
                if (scene == null)
                {
                    return Json(new { IsSuccess = false, Message = HttpContext.InnerLanguage("InvalidScene") });
                }
                else if((bool)takeInverse && !scene.TakeInverse)//如果取反下发，但是该场景没设置容许取反，则提示不下发
                {
                    return Json(new { IsSuccess = false, Message = HttpContext.InnerLanguage("SceneNotTakeInverseIssue") });
                }

				IList<string> offlineRoomNumberList = new List<string>();
				foreach (var host in hostList)
				{
					if (host != null)
					{
						if (host.Status)
						{
                            LightControlManager.ApplyScene(host, scene,(bool)takeInverse);
							roomNumberList.Add(host.RoomNumber);
						}
						else
						{
							offlineRoomNumberList.Add(host.RoomNumber);
						}
					}
				}

                string logDetail = "【" + String.Join(",", roomNumberList) + "】" + "【" + (Language == Language.CN ? scene.Name : scene.EnglishName) + "】";

                SaveSystemLog(AUTHORITY_LightControl, HttpContext.InnerLanguage("SetRoomScene"), logDetail);

				if (offlineRoomNumberList.Count > 0)
				{
					string message = String.Format(HttpContext.InnerLanguage("SendFailedHostOffline"), String.Join(",", offlineRoomNumberList.ToArray()));

					return Json(new { IsSuccess = true, Message = message });
				}

				return Json(new { IsSuccess = true, Message = HttpContext.InnerLanguage("IssuedSuccess") });
			}
			catch (Exception ex)
			{
				SaveSystemLog(AUTHORITY_LightControl, HttpContext.InnerLanguage("SetRoomScene"), ex.Message, false);

				return Json(new { IsSuccess = false, Message = HttpContext.InnerLanguage("IssuedFailedFecause") + ex.Message });
			}
		}

		/// <summary>
		/// 设置灯光状态
		/// </summary>
		/// <param name="hostId"></param>
		/// <param name="modalId"></param>
		/// <param name="onoff"></param>
		/// <param name="brightness"></param>
		/// <returns></returns>
        public ActionResult SetLight(int hostId, int modalId, int status, int brightness, int temperature, int fanSpeed, int mode, int valve)
        {
            try
            {
                var host = HostManager.Get(hostId);
                if (host == null)
                {
                    throw new ApplicationException(HttpContext.InnerLanguage("InvalidRoom"));
                }
                if (!Common.CSRedisCacheHelper.Contains(host.HostNumber, host.MAC))
                {
                    string message = String.Format(HttpContext.InnerLanguage("SendFailedHostOffline"), host.RoomNumber);
                    throw new ApplicationException(message);
                }
                HostModal hostModal = HostModalManager.Get(hostId, modalId);
                if (hostModal == null)
                {
                    throw new ApplicationException(HttpContext.InnerLanguage("InvalidLight"));
                }
                //if (status != 2 && status != 1)
                //{
                //    throw new ApplicationException(HttpContext.InnerLanguage("InvalidState"));
                //}
                //if (brightness < 0 || brightness > 100)
                //{
                //    throw new ApplicationException(HttpContext.InnerLanguage("InvalidBrightness"));
                //}
                HostModalManager.SetDevice(host, hostModal, status, brightness, temperature, fanSpeed, mode, valve);
                System.Text.StringBuilder sb = new System.Text.StringBuilder();
                sb.Append("控制客房(" + host.RoomNumber + ")设备(" + hostModal.Modal.Name + hostModal.Modal.ModalAddress + ")：状态：" + HttpContext.InnerLanguage(status == 1 ? "On" : "Off"));
                if (hostModal.Brightness != brightness)
                {
                    sb.Append("，亮度：" + brightness);
                }
                if (hostModal.SettingTemp != temperature)
                {
                    sb.Append("，温度：" + temperature);
                }
                if (hostModal.FanSpeed != fanSpeed)
                {
                    sb.Append("，风速：" + fanSpeed);
                }
                if (hostModal.Mode != mode)
                {
                    sb.Append("，模式：" + mode);
                }
                if (hostModal.Valve != valve)
                {
                    sb.Append("，阀门：" + valve);
                }
                SaveSystemLog(AUTHORITY_LightControl, HttpContext.InnerLanguage("DeviceControl"), sb.ToString());
                return Json(new { IsSuccess = true, Message = HttpContext.InnerLanguage("SettingSuccess") });
            }
            catch (Exception ex)
            {
                SaveSystemLog(AUTHORITY_LightControl, HttpContext.InnerLanguage("SetRoomLight"), ex.Message, false);
                return Json(new { IsSuccess = false, Message = HttpContext.InnerLanguage("SetFailedbecause") + ex.Message });
            }
        }

		#endregion

		#region Private Methods

		private IList<Host> FindHosts(int? hostID, int? groupID, int? roomStatusID, int? roomTypeID)
		{
			IList<Host> hosts = new List<Host>();

			if (hostID.HasValue)
			{
				hosts.Add(HostManager.Get(hostID.GetValueOrDefault()));
			}
			else
			{
				IList<Group> groups = new List<Group>();
				if (groupID.HasValue)
				{
					groups = GroupManager.GetGroupList(GroupManager.Get(groupID));
				}

				RoomStatus roomStatus = null;
				if (roomStatusID.HasValue)
				{
					roomStatus = RoomStatusManager.Get(roomStatusID);
				}

				RoomType roomType = null;
				if (roomTypeID.HasValue)
				{
					roomType = RoomTypeManager.Get(roomTypeID);
				}

				hosts = HostManager.LoadAll(groups, roomStatus, roomType);
			}

			return hosts;
		}

		#endregion
	}
}
