2022-09-20 13:51:55 +02:00
using System ;
2021-05-13 20:03:07 +02:00
using System.Threading.Tasks ;
2022-08-30 15:42:25 +02:00
using Serilog ;
using TINK.Model.Bikes.BikeInfoNS.BluetoothLock ;
2021-05-13 20:03:07 +02:00
using TINK.Model.Connector ;
2022-08-30 15:42:25 +02:00
using TINK.Model.Device ;
using TINK.Model.User ;
using TINK.MultilingualResources ;
2021-06-26 20:57:55 +02:00
using TINK.Repository.Exception ;
2021-05-13 20:03:07 +02:00
using TINK.Services.BluetoothLock ;
using TINK.Services.BluetoothLock.Exception ;
2022-10-26 20:53:18 +02:00
using TINK.Services.CopriApi.Exception ;
2022-08-30 15:42:25 +02:00
using TINK.Services.Geolocation ;
using TINK.View ;
using IBikeInfoMutable = TINK . Model . Bikes . BikeInfoNS . BluetoothLock . IBikeInfoMutable ;
2021-05-13 20:03:07 +02:00
namespace TINK.ViewModel.Bikes.Bike.BluetoothLock.RequestHandler
{
2023-04-19 12:14:14 +02:00
/// <summary> Bike is reserved, lock is closed and connected to app. </summary>
2022-09-06 16:08:19 +02:00
/// <remarks>
2023-04-19 12:14:14 +02:00
/// Occurs when
/// - bike was reserved out of reach and is in reach now
/// - bike is reserved while in reach
2022-09-06 16:08:19 +02:00
/// </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 ,
2023-04-05 15:02:10 +02:00
IGeolocationService geolocation ,
2022-09-06 16:08:19 +02:00
ILocksService lockService ,
Func < IPollingUpdateTaskManager > viewUpdateManager ,
ISmartDevice smartDevice ,
IViewService viewService ,
IBikesViewModel bikesViewModel ,
IUser activeUser ) : base (
selectedBike ,
AppResources . ActionCancelRequest , // Copri button text: "Reservierung abbrechen"
true , // Show button to enable canceling reservation.
isConnectedDelegate ,
connectorFactory ,
geolocation ,
lockService ,
viewUpdateManager ,
smartDevice ,
viewService ,
bikesViewModel ,
activeUser )
{
LockitButtonText = AppResources . ActionOpenAndBook ; // Button text: "Schloss öffnen & Rad mieten"
IsLockitButtonVisible = true ; // Show "Öffnen" button to enable unlocking
}
/// <summary> Cancel reservation. </summary>
public async Task < IRequestHandler > HandleRequestOption1 ( ) = > await CancelReservation ( ) ;
/// <summary> Open lock and book bike. </summary>
public async Task < IRequestHandler > HandleRequestOption2 ( ) = > await OpenLockAndDoBook ( ) ;
/// <summary> Cancel reservation. </summary>
public async Task < IRequestHandler > CancelReservation ( )
{
BikesViewModel . IsIdle = false ; // Lock list to avoid multiple taps while copri action is pending.
var l_oResult = await ViewService . DisplayAlert (
string . Empty ,
string . Format ( AppResources . QuestionCancelReservation , SelectedBike . GetFullDisplayName ( ) ) ,
AppResources . QuestionAnswerYes ,
AppResources . QuestionAnswerNo ) ;
if ( l_oResult = = false )
{
// User aborted cancel process
Log . ForContext < ReservedClosed > ( ) . Information ( "User selected reserved bike {l_oId} in order to cancel reservation but action was canceled." , SelectedBike . Id ) ;
BikesViewModel . IsIdle = true ;
return this ;
}
Log . ForContext < ReservedClosed > ( ) . Information ( "User selected reserved bike {l_oId} in order to cancel reservation." , SelectedBike . Id ) ;
// Stop polling before cancel request.
BikesViewModel . ActionText = AppResources . ActivityTextOneMomentPlease ;
await ViewUpdateManager ( ) . StopUpdatePeridically ( ) ;
BikesViewModel . ActionText = AppResources . ActivityTextCancelingReservation ;
IsConnected = IsConnectedDelegate ( ) ;
try
{
await ConnectorFactory ( IsConnected ) . Command . DoCancelReservation ( SelectedBike ) ;
2023-04-19 12:14:14 +02:00
// If canceling bike succeeds remove bike because it is not ready to be booked again
2022-09-06 16:08:19 +02:00
IsRemoveBikeRequired = true ;
}
2022-10-26 20:53:18 +02:00
catch ( Exception exception )
2022-09-06 16:08:19 +02:00
{
BikesViewModel . ActionText = string . Empty ;
2022-10-26 20:53:18 +02:00
if ( exception is InvalidAuthorizationResponseException )
2022-09-06 16:08:19 +02:00
{
// Copri response is invalid.
Log . ForContext < BikesViewModel > ( ) . Error ( "User selected reserved bike {l_oId} but canceling reservation failed (Invalid auth. response)." , SelectedBike . Id ) ;
await ViewService . DisplayAlert (
AppResources . MessageCancelReservationBikeErrorGeneralTitle ,
2022-10-26 20:53:18 +02:00
exception . Message ,
2022-09-06 16:08:19 +02:00
AppResources . MessageAnswerOk ) ;
}
2022-10-26 20:53:18 +02:00
else if ( exception is WebConnectFailureException
| | exception is RequestNotCachableException )
2022-09-06 16:08:19 +02:00
{
// Copri server is not reachable.
Log . ForContext < BikesViewModel > ( ) . Information ( "User selected reserved bike {l_oId} but cancel reservation failed (Copri server not reachable)." , SelectedBike . Id ) ;
await ViewService . DisplayAlert (
AppResources . MessageCancelReservationBikeErrorConnectionTitle ,
2022-10-26 20:53:18 +02:00
string . Format ( "{0}\r\n{1}" , exception . Message , WebConnectFailureException . GetHintToPossibleExceptionsReasons ) ,
2022-09-06 16:08:19 +02:00
AppResources . MessageAnswerOk ) ;
}
else
{
2022-10-26 20:53:18 +02:00
Log . ForContext < BikesViewModel > ( ) . Error ( "User selected reserved bike {l_oId} but cancel reservation failed. {@l_oException}." , SelectedBike . Id , exception ) ;
2022-09-06 16:08:19 +02:00
await ViewService . DisplayAlert (
AppResources . MessageCancelReservationBikeErrorGeneralTitle ,
2022-10-26 20:53:18 +02:00
exception . Message ,
2022-09-06 16:08:19 +02:00
AppResources . MessageAnswerOk ) ;
}
BikesViewModel . ActionText = AppResources . ActivityTextStartingUpdater ;
await ViewUpdateManager ( ) . StartUpdateAyncPeridically ( ) ; // Restart polling again.
BikesViewModel . ActionText = string . Empty ;
BikesViewModel . IsIdle = true ; // Unlock GUI
2023-04-05 15:02:10 +02:00
return RequestHandlerFactory . Create ( SelectedBike , IsConnectedDelegate , ConnectorFactory , GeolocationService , LockService , ViewUpdateManager , SmartDevice , ViewService , BikesViewModel , ActiveUser ) ;
2022-09-06 16:08:19 +02:00
}
Log . ForContext < BikesViewModel > ( ) . Information ( "User canceled reservation of bike {l_oId} successfully." , SelectedBike . Id ) ;
// Disconnect lock.
BikesViewModel . ActionText = AppResources . ActivityTextDisconnectingLock ;
try
{
SelectedBike . LockInfo . State = await LockService . DisconnectAsync ( SelectedBike . LockInfo . Id , SelectedBike . LockInfo . Guid ) ;
}
catch ( Exception exception )
{
Log . ForContext < ReservedClosed > ( ) . Error ( "Lock can not be disconnected. {Exception}" , exception ) ;
BikesViewModel . ActionText = AppResources . ActivityTextErrorDisconnect ;
}
BikesViewModel . ActionText = AppResources . ActivityTextStartingUpdater ;
await ViewUpdateManager ( ) . StartUpdateAyncPeridically ( ) ; // Restart polling again.
BikesViewModel . ActionText = string . Empty ;
BikesViewModel . IsIdle = true ; // Unlock GUI
2023-04-05 15:02:10 +02:00
return RequestHandlerFactory . Create ( SelectedBike , IsConnectedDelegate , ConnectorFactory , GeolocationService , LockService , ViewUpdateManager , SmartDevice , ViewService , BikesViewModel , ActiveUser ) ;
2022-09-06 16:08:19 +02:00
}
/// <summary> Open lock and book bike. </summary>
public async Task < IRequestHandler > OpenLockAndDoBook ( )
{
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 selected requested bike {bike} in order to book but action was canceled." , SelectedBike ) ;
BikesViewModel . IsIdle = true ;
return this ;
}
Log . ForContext < ReservedClosed > ( ) . Information ( "User selected requested bike {bike} in order to book but action was canceled." , SelectedBike ) ;
// Stop polling before cancel request.
BikesViewModel . ActionText = AppResources . ActivityTextOneMomentPlease ;
await ViewUpdateManager ( ) . StopUpdatePeridically ( ) ;
// Book bike prior to opening lock.
BikesViewModel . ActionText = AppResources . ActivityTextRentingBike ;
IsConnected = IsConnectedDelegate ( ) ;
try
{
2022-12-27 21:08:09 +01:00
await ConnectorFactory ( IsConnected ) . Command . DoBookAsync ( SelectedBike , LockingAction . Open ) ;
2022-09-06 16:08:19 +02:00
}
catch ( Exception l_oException )
{
BikesViewModel . ActionText = string . Empty ;
if ( l_oException is WebConnectFailureException )
{
// Copri server is not reachable.
Log . ForContext < ReservedClosed > ( ) . Information ( "User selected requested bike {l_oId} but booking failed (Copri server not reachable)." , SelectedBike . Id ) ;
await ViewService . DisplayAdvancedAlert (
AppResources . MessageRentingBikeErrorConnectionTitle ,
WebConnectFailureException . GetHintToPossibleExceptionsReasons ,
l_oException . Message ,
AppResources . MessageAnswerOk ) ;
}
else
{
Log . ForContext < ReservedClosed > ( ) . Error ( "User selected requested bike {l_oId} but reserving failed. {@l_oException}" , SelectedBike . Id , l_oException ) ;
await ViewService . DisplayAdvancedAlert (
AppResources . MessageRentingBikeErrorGeneralTitle ,
string . Empty ,
l_oException . Message ,
AppResources . MessageAnswerOk ) ;
}
BikesViewModel . ActionText = AppResources . ActivityTextStartingUpdater ;
await ViewUpdateManager ( ) . StartUpdateAyncPeridically ( ) ; // Restart polling again.
BikesViewModel . ActionText = string . Empty ;
BikesViewModel . IsIdle = true ; // Unlock GUI
2023-04-05 15:02:10 +02:00
return RequestHandlerFactory . Create ( SelectedBike , IsConnectedDelegate , ConnectorFactory , GeolocationService , LockService , ViewUpdateManager , SmartDevice , ViewService , BikesViewModel , ActiveUser ) ;
2022-09-06 16:08:19 +02:00
}
// Unlock bike.
BikesViewModel . ActionText = AppResources . ActivityTextOpeningLock ;
2022-09-20 13:51:55 +02:00
ILockService btLock ;
2022-09-06 16:08:19 +02:00
try
{
2022-09-20 13:51:55 +02:00
btLock = LockService [ SelectedBike . LockInfo . Id ] ;
SelectedBike . LockInfo . State = ( await btLock . OpenAsync ( ) ) ? . GetLockingState ( ) ? ? LockingState . UnknownDisconnected ;
2022-09-06 16:08:19 +02:00
}
catch ( Exception exception )
{
BikesViewModel . ActionText = string . Empty ;
if ( exception is OutOfReachException )
{
Log . ForContext < ReservedClosed > ( ) . Debug ( "Lock can not be opened. {Exception}" , exception ) ;
await ViewService . DisplayAlert (
AppResources . ErrorOpenLockTitle ,
AppResources . ErrorOpenLockOutOfReachMessage ,
AppResources . MessageAnswerOk ) ;
}
else if ( exception is CouldntOpenBoldIsBlockedException )
{
Log . ForContext < ReservedClosed > ( ) . Debug ( "Lock can not be opened. Bold is blocked. {Exception}" , exception ) ;
await ViewService . DisplayAlert (
AppResources . ErrorOpenLockTitle ,
2023-02-22 14:03:35 +01:00
AppResources . ErrorOpenLockBoldIsBlockedMessage ,
2022-09-06 16:08:19 +02:00
AppResources . MessageAnswerOk ) ;
}
2023-02-22 14:03:35 +01:00
else if ( exception is CouldntOpenBoldStatusIsUnknownException )
2022-09-06 16:08:19 +02:00
{
2023-02-22 14:03:35 +01:00
Log . ForContext < ReservedClosed > ( ) . Debug ( "Lock can not be opened. Bold status is unknown. {Exception}" , exception ) ;
2022-09-06 16:08:19 +02:00
await ViewService . DisplayAlert (
2023-02-22 14:03:35 +01:00
AppResources . ErrorOpenLockStillClosedTitle ,
AppResources . ErrorOpenLockBoldStatusIsUnknownMessage ,
2022-09-06 16:08:19 +02:00
AppResources . MessageAnswerOk ) ;
}
else if ( exception is CouldntOpenInconsistentStateExecption inconsistentState
& & inconsistentState . State = = LockingState . Closed )
{
Log . ForContext < ReservedClosed > ( ) . Debug ( "Lock can not be opened. lock reports state closed. {Exception}" , exception ) ;
await ViewService . DisplayAlert (
AppResources . ErrorOpenLockTitle ,
AppResources . ErrorOpenLockStillClosedMessage ,
AppResources . MessageAnswerOk ) ;
}
else
{
Log . ForContext < ReservedClosed > ( ) . Error ( "Lock can not be opened. {Exception}" , exception ) ;
await ViewService . DisplayAlert (
AppResources . ErrorOpenLockTitle ,
exception . Message ,
AppResources . MessageAnswerOk ) ;
}
SelectedBike . LockInfo . State = exception is StateAwareException stateAwareException
? stateAwareException . State
: LockingState . UnknownDisconnected ;
BikesViewModel . ActionText = AppResources . ActivityTextStartingUpdater ;
await ViewUpdateManager ( ) . StartUpdateAyncPeridically ( ) ; // Restart polling again.
BikesViewModel . ActionText = string . Empty ;
BikesViewModel . IsIdle = true ;
2023-04-05 15:02:10 +02:00
return RequestHandlerFactory . Create ( SelectedBike , IsConnectedDelegate , ConnectorFactory , GeolocationService , LockService , ViewUpdateManager , SmartDevice , ViewService , BikesViewModel , ActiveUser ) ;
2022-09-06 16:08:19 +02:00
}
if ( SelectedBike . LockInfo . State ! = LockingState . Open )
{
// Opening lock failed.
BikesViewModel . ActionText = AppResources . ActivityTextStartingUpdater ;
await ViewUpdateManager ( ) . StartUpdateAyncPeridically ( ) ; // Restart polling again.
BikesViewModel . ActionText = string . Empty ;
BikesViewModel . IsIdle = true ; // Unlock GUI
2023-04-05 15:02:10 +02:00
return RequestHandlerFactory . Create ( SelectedBike , IsConnectedDelegate , ConnectorFactory , GeolocationService , LockService , ViewUpdateManager , SmartDevice , ViewService , BikesViewModel , ActiveUser ) ;
2022-09-06 16:08:19 +02:00
}
BikesViewModel . ActionText = AppResources . ActivityTextReadingChargingLevel ;
try
{
2022-09-20 13:51:55 +02:00
SelectedBike . LockInfo . BatteryPercentage = await btLock . GetBatteryPercentageAsync ( ) ;
2022-09-06 16:08:19 +02:00
}
catch ( Exception exception )
{
if ( exception is OutOfReachException )
{
2023-04-19 12:14:14 +02:00
Log . ForContext < ReservedClosed > ( ) . Debug ( "Battery state can not be read, bike out of range. {Exception}" , exception ) ;
2022-09-06 16:08:19 +02:00
BikesViewModel . ActionText = AppResources . ActivityTextErrorReadingChargingLevelOutOfReach ;
}
else
{
2023-04-19 12:14:14 +02:00
Log . ForContext < ReservedClosed > ( ) . Error ( "Battery state can not be read. {Exception}" , exception ) ;
2022-09-06 16:08:19 +02:00
BikesViewModel . ActionText = AppResources . ActivityTextErrorReadingChargingLevelGeneral ;
}
}
// Lock list to avoid multiple taps while copri action is pending.
BikesViewModel . ActionText = AppResources . ActivityTextStartingUpdatingLockingState ;
2022-09-20 13:51:55 +02:00
var versionTdo = btLock . VersionInfo ;
if ( versionTdo ! = null )
{
SelectedBike . LockInfo . VersionInfo = new VersionInfo . Builder
{
FirmwareVersion = versionTdo . FirmwareVersion ,
HardwareVersion = versionTdo . HardwareVersion ,
LockVersion = versionTdo . LockVersion ,
} . Build ( ) ;
}
2022-09-06 16:08:19 +02:00
IsConnected = IsConnectedDelegate ( ) ;
try
{
await ConnectorFactory ( IsConnected ) . Command . UpdateLockingStateAsync ( SelectedBike ) ;
}
catch ( Exception exception )
{
if ( exception is WebConnectFailureException )
{
// Copri server is not reachable.
Log . ForContext < ReservedClosed > ( ) . Information ( "User locked bike {bike} in order to pause ride but updating failed (Copri server not reachable)." , SelectedBike ) ;
BikesViewModel . ActionText = AppResources . ActivityTextErrorNoWebUpdateingLockstate ;
}
else if ( exception is ResponseException copriException )
{
// Copri server is not reachable.
Log . ForContext < ReservedClosed > ( ) . Information ( "User locked bike {bike} in order to pause ride but updating failed. {response}." , SelectedBike , copriException . Response ) ;
BikesViewModel . ActionText = AppResources . ActivityTextErrorStatusUpdateingLockstate ;
}
else
{
Log . ForContext < ReservedClosed > ( ) . Error ( "User locked bike {bike} in order to pause ride but updating failed . {@l_oException}" , SelectedBike . Id , exception ) ;
BikesViewModel . ActionText = AppResources . ActivityTextErrorConnectionUpdateingLockstate ;
}
}
Log . ForContext < ReservedClosed > ( ) . Information ( "User reserved bike {bike} successfully." , SelectedBike ) ;
BikesViewModel . ActionText = AppResources . ActivityTextStartingUpdater ;
await ViewUpdateManager ( ) . StartUpdateAyncPeridically ( ) ; // Restart polling again.
BikesViewModel . ActionText = string . Empty ;
BikesViewModel . IsIdle = true ; // Unlock GUI
2023-04-05 15:02:10 +02:00
return RequestHandlerFactory . Create ( SelectedBike , IsConnectedDelegate , ConnectorFactory , GeolocationService , LockService , ViewUpdateManager , SmartDevice , ViewService , BikesViewModel , ActiveUser ) ;
2022-09-06 16:08:19 +02:00
}
}
2021-05-13 20:03:07 +02:00
}