using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Domain;
using RCUHost;

namespace Service.Implement
{
	public class ModelManager : GenericManagerBase<Model>, IModelManager
	{
		public IEnergySavingModeReceiver EnergySavingModeReceiver { get; set; }

		public IList<Model> LoadAllByPage(out long total, int page, int rows, string order, string sort)
		{
			return ((Dao.IModelRepository)(this.CurrentRepository)).LoadAllByPage(out total, page, rows, order, sort).ToList();
		}

		public Model GetByName(string name)
		{
			return CurrentRepository.LoadAll().Where(r => r.Name == name).FirstOrDefault();
		}

		public void ApplyModel(Model model, IList<Host> hosts, string user)
		{
			if(hosts.Count == 0){
				return;
			}

			foreach (Host host in hosts)
			{
				EnergySavingModeReceiver.ApplyEnergySavingMode(model, host);
			}

			model.ApplyDate = DateTime.Now;
			model.ApplyUser = user;
			model.Hosts = MergeHostIDs(model.Hosts, hosts.Select(r => r.ID).ToList());

			CurrentRepository.Update(model);
		}

		private string MergeHostIDs(string hostIDs1, IList<int> hostIDs2)
		{
			IList<int> hostIDs = new List<int>();

			if (!String.IsNullOrEmpty(hostIDs1))
			{
				string[] ids = hostIDs1.Split(',');
				hostIDs = ids.Select(r => Convert.ToInt32(r)).ToList();
			}

			return String.Join(",", hostIDs.Union(hostIDs2).ToArray());
		}
	}
}
