using System.Collections.Generic;
using System.Linq;
using Siger.Middlelayer.Common;
using Siger.Middlelayer.ToolRepository.Entities;
using Siger.Middlelayer.ToolRepository.Repositories.Interface;
using Siger.Middlelayer.ToolRepository.Response;

namespace Siger.Middlelayer.ToolRepository.Repositories
{
    internal class SigerprojectToolAlertConditionRepository : ApiToolRepositoryBase<SigerProjectToolAlertCondition>,
        ISigerProjectToolAlertConditionRepository
    {
        private readonly ApiToolDbContext apiToolDbContext;
        public SigerprojectToolAlertConditionRepository(ApiToolDbContext context) : base(context)
        {
            apiToolDbContext = context;
        }

        public List<ResponseToolAlertSetting> GetAlertSettingInfo(int id)
        {
           
            var configData = apiToolDbContext.siger_project_tool_alert_condition.Where(f=> f.cutterlocationid==id);

            var result = from a in apiToolDbContext.siger_alert_condition
                       join n in configData
                       on new { a.condition_param, a.condition_type }
                       equals new { condition_param = n.condition_param.ToString(), condition_type = n.condition_type.ToString() } 
                       into re
                       from r in re.DefaultIfEmpty()
                       where a.status == (int)RowState.Valid
                       select new ResponseToolAlertSetting
                       {
                           condition_type = a.condition_type,
                           condition_param = a.condition_param,
                           condition = a.condition,
                           Default = a.Default,
                           default_m = a.default_m,
                           is_open = r.is_open,
                           k = r.k,
                           m = r.m,
                           cutterlocationid = r.cutterlocationid
                       };
            if (!result.Any())
            {
                throw new BadRequestException(CommonEnum.RecordNotFound);
            }
            return result.OrderBy(f=>f.condition_type).ThenBy(f=>f.condition_param).ToList();
        }
        
    }

}