using Siger.Middlelayer.AccRepository.Entities;
using Siger.Middlelayer.AccRepository.Repositories.Interface;
using Siger.Middlelayer.AccRepository.Response;
using System;
using System.Linq;

using System.Collections.Generic;
using System.Text;
using System.Linq.Expressions;

namespace Siger.Middlelayer.AccRepository.Repositories
{
    internal class AutomationMachineStatusRepository : AccRepositoryBase<siger_automation_machine_status>, IAutomationMachineStatus
    {
        private ApiAccDbContext _context;
        public AutomationMachineStatusRepository(ApiAccDbContext context) : base(context)
        {
            _context = context;
        }

        public IEnumerable<ResponseAutomationMachineStatus> GetSectionStatus(int projectId, int section,List<int>sections)
        {
            var data = from atr in _context.siger_project_machine_attribution 
                       join lv in _context.siger_project_level_section on atr.station equals lv.id
                       join ms in _context.siger_automation_machine_status on lv.id equals ms.section into mstemp
                       join plv in _context.siger_project_level_section on lv.parentid equals plv.id
                       from ms in mstemp.DefaultIfEmpty()
                       select new ResponseAutomationMachineStatus
                       {
                           sectionid = lv.id,
                           section =$"{ plv.title}-{lv.title}",
                           lastupdate = ms!=null? ms.updatetime.ToString():"",
                           enable =ms!=null? ms.enable:1,
                           status =ms!=null? ms.status:1,
                       };

            Expression<Func<ResponseAutomationMachineStatus, bool>> sectionsExpression = f => true;
            if (sections.Any())
            {
                sectionsExpression = q =>sections.Contains(q.sectionid);
            }

            return data.Where(sectionsExpression);
        }
    }
}
