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

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

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

        public void Edit(int id, FmsManualGroup data) {
            var persist = _context.FmsManualGroup
                            .Where(x => x.ManualGroupId == 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.FmsManualGroup.Update(persist);
            _context.SaveChanges();
        }


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

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

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

    }
}