using Microsoft.EntityFrameworkCore;
using ServerManagement.Data;

namespace ServerManagement.Models;

public class ServersEFCoreRepository : IServersEFCoreRepository
{
  private readonly IDbContextFactory<ServerManagementContext> contextFactory;
  public ServersEFCoreRepository(IDbContextFactory<ServerManagementContext> contextFactory) 
  {
    this.contextFactory = contextFactory;
  }

  public void AddServer(Server server)
  {
    using var context = this.contextFactory.CreateDbContext();
    context.Servers.Add(server);

    context.SaveChanges();
  }

  public List<Server> GetServers()
  {
    using var context = this.contextFactory.CreateDbContext();
    return context.Servers.ToList();
  }

  public List<Server> GetServersByCity(string cityName)
  {
    using var context = this.contextFactory.CreateDbContext();
    return context.Servers.Where(s => s.City != null && s.City.ToLower().IndexOf(cityName.ToLower()) >= 0).ToList(); 
  }

  public Server GetServerById(int id)
  {
    using var context = this.contextFactory.CreateDbContext();
    var server = context.Servers.Find(id);

    if (server is not null) return server;
    return new Server();
  }

  public void UpdateServer(int serverId, Server server)
  {
    if (server == null) throw new ArgumentNullException(nameof(server));
    if (serverId != server.Id) return;

    using var context = this.contextFactory.CreateDbContext();
    var serverToUpdate = context.Servers.Find(serverId);

    if (serverToUpdate is not null)
    {
      serverToUpdate.IsOnline = server.IsOnline;
      serverToUpdate.Name = server.Name;
      serverToUpdate.City = server.City;

      context.SaveChanges();
    }
  }

  public void DeleteServer(int serverId)
  {
    using var context = this.contextFactory.CreateDbContext();
    var server = context.Servers.Find(serverId);
    if (server is null) return;

    context.Servers.Remove(server);
    context.SaveChanges();
  }

  public List<Server> SearchServers(string serverFilter)
  {
    using var context = this.contextFactory.CreateDbContext();
    return context.Servers.Where(s => 
      s.Name != null &&
      s.Name.ToLower().IndexOf(serverFilter.ToLower()) >= 0)
      .ToList();
  }
}
