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

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

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

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

            persist.Name = data.Name;
            persist.SortNum = data.SortNum;
            _context.CmFloorCode.Update(persist);
            _context.SaveChanges();
        }


        public void ImportExcel(IList<CmFloorCode> list) {
            using (var transaction = _context.Database.BeginTransaction()) {
                _context.CmFloorCode.AddRange(list);
                _context.SaveChanges();
                transaction.Commit();
            }
        }


        public int checkName(CmFloorCode data, bool isExcel = false) {
            var check = _context.CmFloorCode.Where(x => x.Name == data.Name).Count();
            if (!isExcel && check > 0) {
                throw new ServiceException("이미 동일 정보가 존재합니다.");
            }
            return check;
        }

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

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

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

    }
}