using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using Spring.Data.Core;
using Spring.Data.NHibernate.Generic.Support;
using Domain;

namespace Dao.Implement
{
    public class EnergyConsumptionStatisticsRepository : HibernateDaoSupport, IEnergyConsumptionStatisticsRepository
    {
        public IList<string> LoadRoomNumbers()
        {
            IList<string> roomNumbers = new List<string>();

            IDbCommand cmd = Session.Connection.CreateCommand();

            cmd.CommandText = "SELECT DISTINCT RoomNumber FROM tb_HostModalEnergy ORDER BY RoomNumber";
            cmd.CommandType = CommandType.Text;

            using (IDataReader reader = cmd.ExecuteReader())
            {
                while (reader.Read())
                {
                    roomNumbers.Add(reader["RoomNumber"].ToString());
                }
            }

            return roomNumbers;
        }

        public DataTable LoadModals(string roomNumber, DeviceType? deviceType)
        {
            IList<string> roomNumbers = new List<string>();

            IDbCommand cmd = Session.Connection.CreateCommand();

            string sqlstr = @"WITH HostModalEnergy AS 
								(
									SELECT DISTINCT RoomTypeID,ModalAddress 
									FROM tb_HostModalEnergy E
									WHERE RoomNumber=@RoomNumber ";

            if (deviceType.HasValue)
            {


                sqlstr += "AND EXISTS(SELECT * FROM tb_RoomTypeModal M WHERE E.ModalAddress = M.ModalAddress AND M.Type =@deviceType)";
            }

            sqlstr += @")
					SELECT c.Name 'RoomType',b.ModalAddress,b.Outlet,b.Name,b.EnglishName
					FROM HostModalEnergy a 
					 INNER JOIN tb_RoomTypeModal b ON a.RoomTypeID=b.RoomTypeID AND a.ModalAddress=b.ModalAddress
					 INNER JOIN tb_RoomType c ON c.ID=b.RoomTypeID";

            cmd.CommandText = sqlstr;

            cmd.CommandType = CommandType.Text;

            var parameter = cmd.CreateParameter();
            parameter.ParameterName = "@RoomNumber";
            parameter.DbType = DbType.String;
            parameter.Value = roomNumber;
            cmd.Parameters.Add(parameter);


            if (deviceType.HasValue)
            {
                parameter = cmd.CreateParameter();
                parameter.ParameterName = "@deviceType";
                parameter.DbType = DbType.String;
                parameter.Direction = ParameterDirection.Input;
                parameter.Value = (int)deviceType.GetValueOrDefault();
                cmd.Parameters.Add(parameter);
            }

            IDbDataAdapter da = new SqlDataAdapter((SqlCommand)cmd);

            DataSet ds = new DataSet();
            da.Fill(ds);

            return ds.Tables[0];
        }
    }
}
