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

namespace Siger.Middlelayer.CncRepository.Repositories
{
    internal class MachineStatusTimeSettingRepository : CncRepositoryBase<siger_project_machine_status_timesetting>, IMachineStatusTimeSettingRepository
    {
        private readonly ApiCncDbContext _context;
        public MachineStatusTimeSettingRepository(ApiCncDbContext context) : base(context)
        {
            _context = context;
        }

        public IEnumerable<ResponseGetMachineSetting> GetMachineSettings(IEnumerable<int> machineIds, int projectId)
        {
            var response = new List<ResponseGetMachineSetting>();

            var machines = _context.siger_project_machine.Where(m =>
                m.status == (int) RowState.Valid && m.projectid == projectId
                                                 && machineIds.Contains(m.id) && m.category == (int)MachineCategory.NC);
            foreach (var machine in machines)
            {
                var timesetting = _context.siger_project_machine_status_timesetting.FirstOrDefault(q =>
                    q.childTypeId == machine.typeid && q.projectId == projectId && q.status == (int)RowState.Valid);
                if (timesetting != null)
                {
                    response.Add(new ResponseGetMachineSetting
                    {
                        debugging = timesetting.debugging,
                        fault = timesetting.fault,
                        free = timesetting.free,
                        machineId = machine.id
                    });
                }
            }
            return response;
        }
    }
}
