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

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

        public BuildingService(
            ILogger<BuildingService> logger,
            FMSContext context) {
            _logger = logger;
            _context = context;
        }
        public void Create(CmBuilding data) {
            checkName(data);
            if (_context.CmBuilding.Where(x => x.SiteId == data.SiteId).Count() > 0) {
                throw new ServiceException("하나의 빌딩만 등록할 수 있습니다.");
            }
            data.IsUse = true;
            _context.CmBuilding.Add(data);
            _context.SaveChanges();
        }

        public void Edit(int id, int siteId, CmBuilding data) {

            var persist = _context.CmBuilding
                            .Where(x => x.BuildingId == id && x.SiteId == siteId).FirstOrDefault();
            if (persist == null) {
                throw new ServiceException("정보를 찾을 수 없습니다.");
            }
            if (!persist.Name.Equals(data.Name)) {
                checkName(data);
            }
            persist.SiteId = data.SiteId;
            persist.Name = data.Name;

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


        public void checkName(CmBuilding data) {
            var check = _context.CmBuilding.Where(x => x.SiteId == data.SiteId && x.Name == data.Name).Count();
            if (check > 0) {
                throw new ServiceException("이미 동일 이름이 존재합니다.");
            }
        }
        public void Delete(int id, int siteId) {
            var data = _context.CmBuilding.First(x => x.BuildingId == id && x.SiteId == siteId);
            _context.CmBuilding.Remove(data);
            _context.SaveChanges();
        }

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

        public IQueryable<CmBuilding> Get(int id, int siteId) {
            var data = _context.CmBuilding.Where(x => x.BuildingId == id && x.SiteId == siteId);
            return data;
        }

    }
}