sharee.bike-App/SharedBusinessLogic/Model/Bikes/BikeInfoNS/BluetoothLock/Command/DisconnectCommand.cs
2024-04-09 12:53:23 +02:00

107 lines
2.8 KiB
C#

using System;
using System.Threading.Tasks;
using Serilog;
using ShareeBike.Services.BluetoothLock;
namespace ShareeBike.Model.Bikes.BikeInfoNS.BluetoothLock.Command
{
public static class DisconnectCommand
{
/// <summary>
/// Possible steps of connecting or disconnecting a lock.
/// </summary>
public enum Step
{
DisconnectLock,
}
/// <summary>
/// Possible steps of connecting or disconnecting a lock.
/// </summary>
public enum State
{
GeneralDisconnectError,
}
/// <summary>
/// Interface to notify view model about steps/ state changes of connecting or disconnecting lock process.
/// </summary>
public interface IDisconnectCommandListener
{
/// <summary>
/// Reports current step.
/// </summary>
/// <param name="currentStep">Current step to report.</param>
void ReportStep(Step currentStep);
/// <summary>
/// Reports current state.
/// </summary>
/// <param name="currentState">Current state to report.</param>
/// <param name="message">Message describing the current state.</param>
/// <returns></returns>
Task ReportStateAsync(State currentState, string message);
}
/// <summary>
/// Connect or disconnect lock.
/// </summary>
/// <param name="listener"></param>
/// <returns></returns>
/// <exception cref="Exception"></exception>
public static async Task InvokeAsync<T>(
IBikeInfoMutable bike,
ILocksService lockService,
IDisconnectCommandListener listener = null)
{
// Invokes member to notify about step being started.
void InvokeCurrentStep(Step step)
{
if (listener == null)
return;
try
{
listener.ReportStep(step);
}
catch (Exception exception)
{
Log.ForContext<T>().Error("An exception {@exception} was thrown invoking step-action for step {step} ", exception, step);
}
}
// Invokes member to notify about state change.
async Task InvokeCurrentStateAsync(State state, string message)
{
if (listener == null)
return;
try
{
await listener.ReportStateAsync(state, message);
}
catch (Exception exception)
{
Log.ForContext<T>().Error("An exception {@exception} was thrown invoking state-action for state {state} ", exception, state);
}
}
// Disconnect lock
InvokeCurrentStep(Step.DisconnectLock);
if (bike.LockInfo.State != LockingState.UnknownDisconnected)
{
try
{
bike.LockInfo.State = await lockService.DisconnectAsync(bike.LockInfo.Id, bike.LockInfo.Guid);
Log.ForContext<T>().Information("Lock from bike {bikeId} disconnected successfully.", bike.Id);
}
catch (Exception exception)
{
Log.ForContext<T>().Information("Lock from bike {bikeId} can not be disconnected. {@exception}", bike.Id, exception);
await InvokeCurrentStateAsync(State.GeneralDisconnectError, exception.Message);
}
}
}
}
}