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

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

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

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

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

        public void Delete(int id) {
            var data = _context.FmsManualType.First(x => x.ManualTypeId == id);
            _context.FmsManualType.Remove(data);
            _context.SaveChanges();
        }

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

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

    }
}