using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Dynamic;
using System.Text;
using Domain;
using NHibernate;
using NHibernate.Criterion;
using NHibernate.Hql;
using NHibernate.SqlTypes;

namespace Dao.Implement
{
	public class RoomServiceRecordRepository : RepositoryBase<RoomServiceRecord>, IRoomServiceRecordRepository
	{
		public IList<RoomServiceRecord> LoadAllByPage(out long total, int page, int rows, string order, string sort, string roomNumber, string startTime, string endTime, string[] services)
		{
			ICriteria criteria = Session.CreateCriteria(typeof(RoomServiceRecord));

			if (!String.IsNullOrWhiteSpace(roomNumber))
			{
				criteria.Add(Expression.Like("RoomNumber", "%" + roomNumber + "%"));
			}

			if (!String.IsNullOrWhiteSpace(startTime))
			{
				criteria.Add(Expression.Sql("CONVERT(varchar(16),{alias}.StartTime,120)>=(?)", startTime, NHibernateUtil.String));
            }

            if (!String.IsNullOrWhiteSpace(endTime))
            {
                criteria.Add(Expression.Sql("CONVERT(varchar(16),{alias}.StartTime,120)<=(?)", endTime, NHibernateUtil.String));
            }

            //if (!String.IsNullOrWhiteSpace(endTime))
            //{
            //    criteria.Add(Expression.Sql("CONVERT(varchar(16),{alias}.EndTime,120)=(?)", endTime, NHibernateUtil.String));
            //}

			if (services != null && services.Length > 0)
			{
				criteria.Add(Expression.In("AlarmCode", services));
			}

			var list = criteria.List<RoomServiceRecord>();

			total = list.Count;

			var result = list.AsQueryable().OrderBy(sort + " " + order);

			result = result.Skip((page - 1) * rows).Take(rows);

			return result.ToList();
		}

		public RoomServiceRecord Get(int hostID, string alarmCode, bool status)
		{
			return LoadAll().FirstOrDefault(r => r.HostID == hostID && r.AlarmCode == alarmCode && r.Status == status);
		}

		public RoomServiceRecord CreateServiceRecord(Host host, AlarmSetting abnormitySetting)
		{
			var abnormityRecord = new RoomServiceRecord();
			abnormityRecord.HostID = host.ID;
			abnormityRecord.RoomNumber = host.RoomNumber;
			abnormityRecord.AlarmCode = abnormitySetting.Code;
			abnormityRecord.Name = abnormitySetting.Name;
			abnormityRecord.Status = true;
			abnormityRecord.StartTime = DateTime.Now;
			return abnormityRecord;
		}
	}
}
