KoogleApp/KoogleApp/Store/Game/ThrowPanel/Effects.cs

104 lines
3.2 KiB
C#

using Fluxor;
using KoogleApp.Hub;
using KoogleApp.Model;
using KoogleApp.Services;
using System.Text.Json;
namespace KoogleApp.Store.Game.ThrowPanel
{
public class ThrowPanelEffects : IDisposable
{
private readonly ILogger<ThrowPanelEffects> _logger;
private readonly HubConnectionService _sharedModelHub;
private readonly IState<ThrowPanelState> _state;
private readonly SessionStorage _sessionStorage;
private readonly string _dataFilePath = "ThrowPanelState.json";
public ThrowPanelEffects(
ILogger<ThrowPanelEffects> logger,
HubConnectionService sharedModelHub, IState<ThrowPanelState> state,
SessionStorage sessionStorage)
{
_logger = logger;
_sharedModelHub = sharedModelHub;
_state = state;
_sessionStorage = sessionStorage;
}
public void Dispose()
{
//_sharedModelHub?.Dispose();
}
//[EffectMethod(typeof(StartAction))]
[EffectMethod]
public async Task HandleStartAction(StartAction action, IDispatcher dispatcher)
{
dispatcher.Dispatch(new BroadcastThrowPanelStateAction(_state.Value));
}
[EffectMethod]
public async Task HandleConnectToHubAction(ConnectToHubAction action, IDispatcher dispatcher)
{
try
{
await _sharedModelHub.ConnectToHub(dispatcher);
}
catch (Exception ex)
{
_logger.LogError(ex, "Failed to connect to hub");
//dispatcher.Dispatch(new HubConnectionFailedAction(ex.Message));
}
}
[EffectMethod]
public async Task HandelLoadStateAction(LoadStateFromSessionAction stateFromSessionAction, IDispatcher dispatcher)
{
var state = await _sessionStorage.GetThrowPanelStateAsync();
if (state == null)
{
try
{
if (File.Exists(_dataFilePath))
{
var json = await File.ReadAllTextAsync(_dataFilePath);
state = JsonSerializer.Deserialize<ThrowPanelState>(json);
}
}
catch (Exception e)
{
// TODO error handling
}
}
if (state != null)
{
dispatcher.Dispatch(new StateLoadedAction(state));
}
}
[EffectMethod]
public async Task HandelBroadcastThrowPanelStateAction(BroadcastThrowPanelStateAction action, IDispatcher dispatcher)
{
await _sessionStorage.SetThrowPanelStateAsync(action.State);
try
{
var json = JsonSerializer.Serialize(action.State, new JsonSerializerOptions
{
WriteIndented = true
});
await File.WriteAllTextAsync(_dataFilePath, json);
}
catch (Exception ex)
{
// TODO error handling
}
await _sharedModelHub.HandleStartAction(new StartAction(_state.Value), dispatcher);
}
}
}