using System.Linq;
using FMSAdmin.Data;
using FMSAdmin.Entities;
using Microsoft.Extensions.Logging;

namespace FMSAdmin.Services {
    public class EquipmentCodeTypeService {
        private readonly ILogger<EquipmentCodeTypeService> _logger;
        private readonly FMSContext _context;

        public EquipmentCodeTypeService(
            ILogger<EquipmentCodeTypeService> logger,
            FMSContext context) {
            _logger = logger;
            _context = context;
        }
        public void Create(FmsEquipmentCodeType data) {
            checkName(data);
            data.IsUse = true;
            _context.FmsEquipmentCodeType.Add(data);
            _context.SaveChanges();
        }

        public void Edit(int id, FmsEquipmentCodeType data) {
            var persist = _context.FmsEquipmentCodeType
                            .Where(x => x.EquipmentTypeId == id).FirstOrDefault();
            if (persist == null) {
                throw new ServiceException("정보를 찾을 수 없습니다.");
            }
            if (!persist.Name.Equals(data.Name)) {
                checkName(data);
            }
            persist.Name = data.Name;
            persist.Description = data.Description;
            _context.FmsEquipmentCodeType.Update(persist);
            _context.SaveChanges();
        }
        public void checkName(FmsEquipmentCodeType data) {
            var check = _context.FmsEquipmentCodeType.Where(x => x.Name == data.Name).Count();
            if (check > 0) {
                throw new ServiceException("이미 동일 정보가 존재합니다.");
            }
        }
        public void Delete(int id) {
            var data = _context.FmsEquipmentCodeType.First(x => x.EquipmentTypeId == id);
            _context.FmsEquipmentCodeType.Remove(data);
            _context.SaveChanges();
        }

        public IQueryable<FmsEquipmentCodeType> GetAll() {
            var query = _context.FmsEquipmentCodeType;
            return query;
        }

        public IQueryable<FmsEquipmentCodeType> Get(int id) {
            var data = _context.FmsEquipmentCodeType.Where(x => x.EquipmentTypeId == id);
            return data;
        }

    }
}