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

namespace WebSite.Controllers
{
    public class CoulometricStatisticsController : BaseController
	{
		public IOverviewManager OverviewManager { get; set; }

		public IEnergyConsumptionStatisticsManager EnergyConsumptionStatisticsManager { get; set; }

		#region Actions

		public ActionResult Index()      
        {
            return View();
		}

		public ActionResult LoadRoomNumbers()
		{
			IList<object> result = new List<object>();

			IList<string> roomNumbers = EnergyConsumptionStatisticsManager.LoadRoomNumbers();

			foreach (string roomNumber in roomNumbers)
			{
				result.Add(new { Value = roomNumber, Name = roomNumber });
			}

			return Json(result, JsonRequestBehavior.AllowGet);
		}

        public ActionResult LoadModals(string roomNumber, DeviceType? deviceType)
		{
            var table = EnergyConsumptionStatisticsManager.LoadModals(roomNumber, deviceType);

			var list = new List<object>();

			foreach (DataRow row in table.Rows)
			{
				list.Add(new
				{
					RoomType = row["RoomType"],
					ModalAddress = row["ModalAddress"],
					Outlet = row["Outlet"],
					Name = (Language == Language.CN) ? row["Name"] : row["EnglishName"]
				});
			}

			return Json(new { total = list.Count, rows = list });
		}

		/// <summary>
		/// 加载图表数据
		/// </summary>
		/// <param name="roomNumber"></param>
		/// <param name="dateUint"></param>
		/// <param name="startDate"></param>
		/// <param name="endDate"></param>
		/// <returns></returns>
		public ActionResult LoadChartData(string roomNumbers, DateTimeUnit dateUnit, string startDate, string endDate, DeviceType? deviceType, string modalIds)
		{
			try
			{
				var table = OverviewManager.LoadEnergyStatitics(roomNumbers, dateUnit, startDate, endDate, deviceType, modalIds);

				IList<string> legend = new List<string>();

				IList<object> data = new List<object>();

				IList<string> xAxis = new List<string>();

				for (int i = 1; i < table.Columns.Count; i++)
				{
					xAxis.Add(table.Columns[i].ToString());
				}

				foreach (DataRow row in table.Rows)
				{
					string name = row["回路"].ToString();

					legend.Add(name);

					IList<float> data1 = new List<float>();

					for (int i = 1; i < table.Columns.Count; i++)
					{
						data1.Add(Convert.ToSingle(row[i]));
					}

					data.Add(new { name = name, data = data1 });
				}

				return Json(new { IsSuccess = true, Legend = legend, XAxis = xAxis, Data = data });
			}
			catch (Exception ex)
			{
				if (ex.GetType() == typeof(IndexOutOfRangeException)) 
				{
					return Json(new { IsSuccess = false, Message = HttpContext.InnerLanguage("NotFoundData") });
				}
				return Json(new { IsSuccess = false, Message = HttpContext.InnerLanguage("LoadDataFailedBecause") + ex.Message });
			}
		}

		#endregion
	}
}
