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

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

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

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

            persist.SiteId = data.SiteId;
            persist.BuildingId = data.BuildingId;
            persist.FloorId = data.FloorId;
            persist.Name = data.Name;

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


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

        public int checkName(CmZone data, bool isExcel = false) {
            var check = _context.CmZone.Where(x => x.SiteId == data.SiteId && x.BuildingId == data.BuildingId && x.FloorId == data.FloorId && x.Name == data.Name).Count();
            if (!isExcel && check > 0) {
                throw new ServiceException("이미 동일 정보가 존재합니다.(빌딩명칭, 층 명칭, 구역 명칭 확인 필요)");
            }
            return check;
        }

        public void Delete(int id, int siteId) {
            var data = _context.CmZone.First(x => x.ZoneId == id && x.SiteId == siteId);
            _context.CmZone.Remove(data);
            _context.SaveChanges();
        }

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

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

    }
}