PalacePal/Pal.Client/Floors/Tasks/SaveNewLocations.cs

77 lines
2.6 KiB
C#
Raw Normal View History

2023-02-18 20:12:36 +00:00
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
2023-02-18 20:12:36 +00:00
using Pal.Client.Database;
using Pal.Common;
2023-03-30 20:01:43 +00:00
namespace Pal.Client.Floors.Tasks;
internal sealed class SaveNewLocations : DbTask<SaveNewLocations>
2023-02-18 20:12:36 +00:00
{
2023-03-30 20:01:43 +00:00
private readonly MemoryTerritory _territory;
private readonly List<PersistentLocation> _newLocations;
public SaveNewLocations(IServiceScopeFactory serviceScopeFactory, MemoryTerritory territory,
List<PersistentLocation> newLocations)
: base(serviceScopeFactory)
2023-02-18 20:12:36 +00:00
{
2023-03-30 20:01:43 +00:00
_territory = territory;
_newLocations = newLocations;
}
2023-02-18 20:12:36 +00:00
2023-03-30 20:01:43 +00:00
protected override void Run(PalClientContext dbContext, ILogger<SaveNewLocations> logger)
{
Run(_territory, dbContext, logger, _newLocations);
}
2023-02-18 20:12:36 +00:00
2023-03-30 20:01:43 +00:00
public static void Run<T>(
MemoryTerritory territory,
PalClientContext dbContext,
ILogger<T> logger,
List<PersistentLocation> locations)
{
lock (territory.LockObj)
2023-02-18 20:12:36 +00:00
{
2023-03-30 20:01:43 +00:00
logger.LogInformation("Saving {Count} new locations for territory {Territory}", locations.Count,
territory.TerritoryType);
2023-02-18 20:12:36 +00:00
2023-03-30 20:01:43 +00:00
Dictionary<PersistentLocation, ClientLocation> mapping =
locations.ToDictionary(x => x, x => ToDatabaseLocation(x, territory.TerritoryType));
dbContext.Locations.AddRange(mapping.Values);
dbContext.SaveChanges();
2023-03-30 20:01:43 +00:00
foreach ((PersistentLocation persistentLocation, ClientLocation clientLocation) in mapping)
{
persistentLocation.LocalId = clientLocation.LocalId;
2023-02-18 20:12:36 +00:00
}
}
2023-03-30 20:01:43 +00:00
}
2023-02-18 20:12:36 +00:00
2023-03-30 20:01:43 +00:00
private static ClientLocation ToDatabaseLocation(PersistentLocation location, ETerritoryType territoryType)
{
return new ClientLocation
2023-02-18 20:12:36 +00:00
{
2023-03-30 20:01:43 +00:00
TerritoryType = (ushort)territoryType,
Type = ToDatabaseType(location.Type),
X = location.Position.X,
Y = location.Position.Y,
Z = location.Position.Z,
Seen = location.Seen,
Source = location.Source,
SinceVersion = typeof(Plugin).Assembly.GetName().Version!.ToString(2),
};
}
2023-02-18 20:12:36 +00:00
2023-03-30 20:01:43 +00:00
private static ClientLocation.EType ToDatabaseType(MemoryLocation.EType type)
{
return type switch
2023-02-18 20:12:36 +00:00
{
2023-03-30 20:01:43 +00:00
MemoryLocation.EType.Trap => ClientLocation.EType.Trap,
MemoryLocation.EType.Hoard => ClientLocation.EType.Hoard,
_ => throw new ArgumentOutOfRangeException(nameof(type), type, null)
};
2023-02-18 20:12:36 +00:00
}
}