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

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

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

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

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


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

        }

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

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

    }
}