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



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

        public MonitoringPointLocationService(
            ILogger<MonitoringPointLocationService> logger,
            FMSContext context,
            StorageHelper storage
        ) {
            _logger = logger;
            _context = context;
            _storage = storage;
        }

        public IQueryable<BemsMonitoringPoint> GetAll() {
            var query = _context.BemsMonitoringPoint;//.AsNoTracking();
            return query;


        }

        public IQueryable<BemsMonitoringPoint> Get(int siteId, int facilityCode, int propertyId) {
            var data = _context.BemsMonitoringPoint.Where(x => x.SiteId == siteId && x.FacilityCode == facilityCode && x.PropertyId == propertyId);
            return data;
        }

        public void Edit(int siteId, ICollection<PointToLocation> data) {
            using (var transaction = _context.Database.BeginTransaction()) {
                foreach (var location in data) {
                    var foundQuery = _context.BemsMonitoringPoint.Where(x => x.SiteId == location.SiteId && x.FacilityCode == location.FacilityCode && x.PropertyId == location.PropertyId);
                    if (foundQuery.Any() == false) continue;

                    var found = foundQuery.First();
                    found.BuildingId = location.BuildingId;
                    if (location.FloorId != 0) {
                        found.FloorId = location.FloorId;
                    }
                    if (location.ZoneId != 0) {
                        found.ZoneId = location.ZoneId;
                    }

                    _context.BemsMonitoringPoint.Update(found);
                }
                _context.SaveChanges();

                transaction.Commit();
            }
        }

        public void Delete(List<BemsMonitoringPoint> data) {
            using (var transaction = _context.Database.BeginTransaction()) {
                foreach (var point in data) {
                    var persist = _context.BemsMonitoringPoint.First(x => x.SiteId == point.SiteId && x.FacilityCode == point.FacilityCode && x.PropertyId == point.PropertyId);
                    persist.BuildingId = null;
                    persist.FloorId = null;
                    persist.ZoneId = null;
                    _context.BemsMonitoringPoint.Update(persist);
                }
                _context.SaveChanges();

                transaction.Commit();
            }
        }
    }
}