sharee.bike-App/TINKLib/ViewModel/Bikes/Bike/BluetoothLock/RequestHandler/ReservedClosed.cs
2023-11-06 12:23:09 +01:00

360 lines
14 KiB
C#

using System;
using System.Threading.Tasks;
using Serilog;
using TINK.Model.Bikes.BikeInfoNS.BluetoothLock;
using TINK.Model.Connector;
using TINK.Model.Device;
using TINK.Model.User;
using TINK.MultilingualResources;
using TINK.Repository.Exception;
using TINK.Services.BluetoothLock;
using TINK.Services.BluetoothLock.Exception;
using TINK.Services.CopriApi.Exception;
using TINK.Services.Geolocation;
using TINK.View;
using IBikeInfoMutable = TINK.Model.Bikes.BikeInfoNS.BluetoothLock.IBikeInfoMutable;
namespace TINK.ViewModel.Bikes.Bike.BluetoothLock.RequestHandler
{
/// <summary> Bike is reserved, lock is closed and connected to app. </summary>
/// <remarks>
/// Occurs when
/// - bike was reserved out of reach and is in reach now
/// - bike is reserved while in reach
/// </remarks>
public class ReservedClosed : Base, IRequestHandler
{
/// <param name="smartDevice">Provides info about the smart device (phone, tablet, ...)</param>
/// <param name="bikesViewModel">View model to be used for progress report and unlocking/ locking view.</param>
public ReservedClosed(
IBikeInfoMutable selectedBike,
Func<bool> isConnectedDelegate,
Func<bool, IConnector> connectorFactory,
IGeolocationService geolocation,
ILocksService lockService,
Func<IPollingUpdateTaskManager> viewUpdateManager,
ISmartDevice smartDevice,
IViewService viewService,
IBikesViewModel bikesViewModel,
IUser activeUser) : base(
selectedBike,
AppResources.ActionCancelReservation, // Cancel Reservation
true, // Show button "Cancel Reservation"
isConnectedDelegate,
connectorFactory,
geolocation,
lockService,
viewUpdateManager,
smartDevice,
viewService,
bikesViewModel,
activeUser)
{
LockitButtonText = AppResources.ActionOpenLockAndRentBike; // Open Lock & Rent Bike
IsLockitButtonVisible = true; // Show button "Open Lock & Rent Bike"
}
/// <summary> Cancel reservation. </summary>
public async Task<IRequestHandler> HandleRequestOption1() => await CancelReservation();
/// <summary> Open lock and rent bike. </summary>
public async Task<IRequestHandler> HandleRequestOption2() => await OpenLockAndRentBike();
/// <summary> Cancel reservation. </summary>
public async Task<IRequestHandler> CancelReservation()
{
Log.ForContext<ReservedClosed>().Information("User request to cancel reservation of bike {bikeId}", SelectedBike.Id);
BikesViewModel.IsIdle = false; // Lock list to avoid multiple taps while copri action is pending.
var result = await ViewService.DisplayAlert(
string.Empty,
string.Format(AppResources.QuestionCancelReservation, SelectedBike.GetFullDisplayName()),
AppResources.MessageAnswerYes,
AppResources.MessageAnswerNo);
if (result == false)
{
// User aborted cancel process
Log.ForContext<ReservedClosed>().Information("User canceled request to cancel reservation of bike {bikeId}.", SelectedBike.Id);
BikesViewModel.IsIdle = true;
return this;
}
// Stop polling before cancel request.
BikesViewModel.ActionText = AppResources.ActivityTextOneMomentPlease;
await ViewUpdateManager().StopAsync();
BikesViewModel.ActionText = AppResources.ActivityTextCancelingReservation;
IsConnected = IsConnectedDelegate();
try
{
await ConnectorFactory(IsConnected).Command.DoCancelReservation(SelectedBike);
Log.ForContext<ReservedClosed>().Information("User canceled reservation of bike {bikeId} successfully.", SelectedBike.Id);
}
catch (Exception exception)
{
BikesViewModel.ActionText = string.Empty;
Log.ForContext<ReservedClosed>().Information("Canceling reservation of bike {bikeId} failed.", SelectedBike.Id);
if (exception is InvalidAuthorizationResponseException)
{
// Copri response is invalid.
Log.ForContext<ReservedClosed>().Error("Invalid auth. response.");
await ViewService.DisplayAlert(
AppResources.ErrorCancelReservationTitle,
AppResources.ErrorAccountInvalidAuthorization,
AppResources.MessageAnswerOk);
}
else if (exception is WebConnectFailureException
|| exception is RequestNotCachableException)
{
// Copri server is not reachable.
Log.ForContext<ReservedClosed>().Error("Copri server not reachable.");
await ViewService.DisplayAlert(
AppResources.ErrorCancelReservationTitle,
AppResources.ErrorNoWeb,
AppResources.MessageAnswerOk);
}
else
{
Log.ForContext<ReservedClosed>().Error("{@exception}", exception);
await ViewService.DisplayAdvancedAlert(
AppResources.ErrorCancelReservationTitle,
exception.Message,
AppResources.ErrorTryAgain,
AppResources.MessageAnswerOk);
}
BikesViewModel.ActionText = AppResources.ActivityTextStartingUpdater;
await ViewUpdateManager().StartAsync(); // Restart polling again.
BikesViewModel.ActionText = string.Empty;
BikesViewModel.IsIdle = true; // Unlock GUI
return RequestHandlerFactory.Create(SelectedBike, IsConnectedDelegate, ConnectorFactory, GeolocationService, LockService, ViewUpdateManager, SmartDevice, ViewService, BikesViewModel, ActiveUser);
}
// Disconnect lock.
BikesViewModel.ActionText = AppResources.ActivityTextDisconnectingLock;
try
{
SelectedBike.LockInfo.State = await LockService.DisconnectAsync(SelectedBike.LockInfo.Id, SelectedBike.LockInfo.Guid);
Log.ForContext<ReservedClosed>().Information("Lock from bike {bikeId} disconnected successfully.", SelectedBike.Id);
}
catch (Exception disconnectException)
{
Log.ForContext<ReservedClosed>().Information("Lock from bike {bikeId} can not be disconnected. {@exception}", SelectedBike.Id, disconnectException);
BikesViewModel.ActionText = AppResources.ActivityTextErrorDisconnect;
}
BikesViewModel.ActionText = AppResources.ActivityTextStartingUpdater;
await ViewUpdateManager().StartAsync(); // Restart polling again.
BikesViewModel.ActionText = string.Empty;
BikesViewModel.IsIdle = true; // Unlock GUI
return RequestHandlerFactory.Create(SelectedBike, IsConnectedDelegate, ConnectorFactory, GeolocationService, LockService, ViewUpdateManager, SmartDevice, ViewService, BikesViewModel, ActiveUser);
}
/// <summary> Open lock and rent bike. </summary>
public async Task<IRequestHandler> OpenLockAndRentBike()
{
Log.ForContext<ReservedClosed>().Information("User request to book and open bike {bikeId}.", SelectedBike.Id);
BikesViewModel.IsIdle = false;
// Ask whether to really book bike?
var alertResult = await ViewService.DisplayAlert(
string.Empty,
string.Format(AppResources.QuestionOpenLockAndBookBike, SelectedBike.GetFullDisplayName()),
AppResources.MessageAnswerYes,
AppResources.MessageAnswerNo);
if (alertResult == false)
{
// User aborted booking process
Log.ForContext<ReservedClosed>().Information("User canceled request to book bike {bikeId}.", SelectedBike.Id);
BikesViewModel.IsIdle = true;
return this;
}
// Stop polling before cancel request.
BikesViewModel.ActionText = AppResources.ActivityTextOneMomentPlease;
await ViewUpdateManager().StopAsync();
// Book bike prior to opening lock.
BikesViewModel.ActionText = AppResources.ActivityTextRentingBike;
IsConnected = IsConnectedDelegate();
try
{
await ConnectorFactory(IsConnected).Command.DoBookAsync(SelectedBike, LockingAction.Open);
Log.ForContext<ReservedClosed>().Information("User booked bike {bikeId} successfully.", SelectedBike.Id);
}
catch (Exception exception)
{
BikesViewModel.ActionText = string.Empty;
Log.ForContext<ReservedClosed>().Information("Booking of bike {bikeId} failed.", SelectedBike.Id);
if (exception is WebConnectFailureException)
{
// Copri server is not reachable.
Log.ForContext<ReservedClosed>().Error("Copri server not reachable.");
await ViewService.DisplayAlert(
AppResources.ErrorRentingBikeTitle,
AppResources.ErrorNoWeb,
AppResources.MessageAnswerOk);
}
else
{
Log.ForContext<ReservedClosed>().Error("{@exception}", exception);
await ViewService.DisplayAdvancedAlert(
AppResources.ErrorRentingBikeTitle,
AppResources.ErrorTryAgain,
exception.Message,
AppResources.MessageAnswerOk);
}
BikesViewModel.ActionText = AppResources.ActivityTextStartingUpdater;
await ViewUpdateManager().StartAsync(); // Restart polling again.
BikesViewModel.ActionText = string.Empty;
BikesViewModel.IsIdle = true; // Unlock GUI
return RequestHandlerFactory.Create(SelectedBike, IsConnectedDelegate, ConnectorFactory, GeolocationService, LockService, ViewUpdateManager, SmartDevice, ViewService, BikesViewModel, ActiveUser);
}
// Unlock bike.
BikesViewModel.ActionText = AppResources.ActivityTextOpeningLock;
ILockService btLock = LockService[SelectedBike.LockInfo.Id];
try
{
SelectedBike.LockInfo.State = (await btLock.OpenAsync())?.GetLockingState() ?? LockingState.UnknownDisconnected;
Log.ForContext<ReservedClosed>().Information("Lock from {bikeId} opened successfully.",SelectedBike.Id);
}
catch (Exception exception)
{
Log.ForContext<ReservedClosed>().Information("Lock from {bikeId} can not be opened.", SelectedBike.Id);
BikesViewModel.ActionText = string.Empty;
if (exception is OutOfReachException)
{
Log.ForContext<ReservedClosed>().Debug("Lock is out of reach.");
await ViewService.DisplayAdvancedAlert(
AppResources.ErrorOpenLockTitle,
AppResources.ErrorLockOutOfReach,
AppResources.ErrorOpenLockBikeAlreadyBooked,
AppResources.MessageAnswerOk);
}
else if (exception is CouldntOpenBoldIsBlockedException)
{
Log.ForContext<ReservedClosed>().Debug("Bold is blocked.");
await ViewService.DisplayAdvancedAlert(
AppResources.ErrorOpenLockTitle,
AppResources.ErrorOpenLockBoldBlocked,
AppResources.ErrorOpenLockBikeAlreadyBooked,
AppResources.MessageAnswerOk);
}
else if (exception is CouldntOpenBoldStatusIsUnknownException)
{
Log.ForContext<ReservedClosed>().Debug("Bold status is unknown.");
await ViewService.DisplayAdvancedAlert(
AppResources.ErrorOpenLockTitle,
AppResources.ErrorOpenLockStatusUnknown,
AppResources.ErrorOpenLockBikeAlreadyBooked,
AppResources.MessageAnswerOk);
}
else if (exception is CouldntOpenInconsistentStateExecption inconsistentState
&& inconsistentState.State == LockingState.Closed)
{
Log.ForContext<ReservedClosed>().Debug("Lock reports that it is still closed.");
await ViewService.DisplayAdvancedAlert(
AppResources.ErrorOpenLockTitle,
AppResources.ErrorOpenLockStillClosed,
AppResources.ErrorOpenLockBikeAlreadyBooked,
AppResources.MessageAnswerOk);
}
else
{
Log.ForContext<ReservedClosed>().Debug("{@exception}", exception);
await ViewService.DisplayAdvancedAlert(
AppResources.ErrorOpenLockTitle,
AppResources.ErrorTryAgain,
exception.Message,
AppResources.MessageAnswerOk);
}
SelectedBike.LockInfo.State = exception is StateAwareException stateAwareException
? stateAwareException.State
: LockingState.UnknownDisconnected;
}
// get current charging level
BikesViewModel.ActionText = AppResources.ActivityTextReadingChargingLevel;
try
{
SelectedBike.LockInfo.BatteryPercentage = await btLock.GetBatteryPercentageAsync();
Log.ForContext<ReservedClosed>().Information("Battery state of lock from {bikeId} read successfully.", SelectedBike.Id);
}
catch (Exception exception)
{
Log.ForContext<ReservedClosed>().Information("Battery state of lock from {bikeId} can not be read.", SelectedBike.Id);
if (exception is OutOfReachException)
{
Log.ForContext<ReservedClosed>().Debug("Lock is out of reach.");
BikesViewModel.ActionText = AppResources.ActivityTextErrorReadingChargingLevelOutOfReach;
}
else
{
Log.ForContext<ReservedClosed>().Debug("{@exception}", exception);
BikesViewModel.ActionText = AppResources.ActivityTextErrorReadingChargingLevelGeneral;
}
}
// get lock infos.
BikesViewModel.ActionText = AppResources.ActivityTextStartingUpdatingLockingState;
var versionTdo = btLock.VersionInfo;
if (versionTdo != null)
{
SelectedBike.LockInfo.VersionInfo = new VersionInfo.Builder
{
FirmwareVersion = versionTdo.FirmwareVersion,
HardwareVersion = versionTdo.HardwareVersion,
LockVersion = versionTdo.LockVersion,
}.Build();
}
// update backend
IsConnected = IsConnectedDelegate();
try
{
await ConnectorFactory(IsConnected).Command.UpdateLockingStateAsync(SelectedBike);
Log.ForContext<ReservedClosed>().Information("Backend updated for bike {bikeId} successfully.", SelectedBike.Id);
}
catch (Exception exception)
{
Log.ForContext<ReservedClosed>().Information("Updating backend for bike {bikeId} failed.", SelectedBike.Id);
if (exception is WebConnectFailureException)
{
// No web.
Log.ForContext<ReservedClosed>().Debug("Copri server not reachable. No web.");
BikesViewModel.ActionText = AppResources.ActivityTextErrorNoWebUpdateingLockstate;
}
else if (exception is ResponseException copriException)
{
// Copri exception.
Log.ForContext<ReservedClosed>().Debug("{response}", copriException.Response);
BikesViewModel.ActionText = AppResources.ActivityTextErrorStatusUpdateingLockstate;
}
else
{
Log.ForContext<ReservedClosed>().Debug("{@exception}", exception);
BikesViewModel.ActionText = AppResources.ActivityTextErrorConnectionUpdateingLockstate;
}
}
BikesViewModel.ActionText = AppResources.ActivityTextStartingUpdater;
await ViewUpdateManager().StartAsync(); // Restart polling again.
BikesViewModel.ActionText = string.Empty;
BikesViewModel.IsIdle = true; // Unlock GUI
return RequestHandlerFactory.Create(SelectedBike, IsConnectedDelegate, ConnectorFactory, GeolocationService, LockService, ViewUpdateManager, SmartDevice, ViewService, BikesViewModel, ActiveUser);
}
}
}