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

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

        public AccidentCodeTypeService(
            ILogger<AccidentCodeTypeService> logger,
            FMSContext context) {
            _logger = logger;
            _context = context;
        }
        public void Create(FmsAccidentCodeType data) {
            checkName(data);
            _context.FmsAccidentCodeType.Add(data);
            _context.SaveChanges();
        }

        public void Edit(int id, FmsAccidentCodeType data) {
            var persist = _context.FmsAccidentCodeType
                            .Where(x => x.AccidentTypeId == id).FirstOrDefault();
            if (persist == null) {
                throw new ServiceException("정보를 찾을 수 없습니다.");
            }
            if (!persist.Name.Equals(data.Name)) {
                checkName(data);
            }
            persist.Name = data.Name;
            persist.IsUse = data.IsUse;

            _context.FmsAccidentCodeType.Update(persist);
            _context.SaveChanges();
        }


        public void checkName(FmsAccidentCodeType data) {
            var check = _context.FmsAccidentCodeType.Where(x => x.Name == data.Name).Count();
            if (check > 0) {
                throw new ServiceException("이미 동일 정보가 존재합니다.");
            }
        }
        public void Delete(int id) {
            var data = _context.FmsAccidentCodeType.First(x => x.AccidentTypeId == id);
            _context.FmsAccidentCodeType.Remove(data);
            _context.SaveChanges();

        }

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

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

    }
}