2021-05-13 20:03:07 +02:00
using System ;
using Serilog ;
using System.Threading.Tasks ;
using TINK.Model.Bike.BluetoothLock ;
using TINK.Model.Connector ;
using TINK.Model.State ;
using TINK.View ;
2021-06-26 20:57:55 +02:00
using TINK.Repository.Exception ;
2021-05-13 20:03:07 +02:00
using TINK.Model.Services.Geolocation ;
using TINK.Services.BluetoothLock ;
using TINK.Services.BluetoothLock.Tdo ;
using TINK.MultilingualResources ;
using TINK.Model.Bikes.Bike.BluetoothLock ;
using TINK.Services.BluetoothLock.Exception ;
using TINK.Model.User ;
2021-06-26 20:57:55 +02:00
using TINK.Model.Device ;
2021-05-13 20:03:07 +02:00
namespace TINK.ViewModel.Bikes.Bike.BluetoothLock.RequestHandler
{
public class DisposableDisconnected : Base , IRequestHandler
{
2021-06-26 20:57:55 +02:00
/// <param name="smartDevice">Provides info about the smart device (phone, tablet, ...).</param>
2021-05-13 20:03:07 +02:00
/// <param name="bikesViewModel">View model to be used for progress report and unlocking/ locking view.</param>
public DisposableDisconnected (
IBikeInfoMutable selectedBike ,
Func < bool > isConnectedDelegate ,
Func < bool , IConnector > connectorFactory ,
IGeolocation geolocation ,
ILocksService lockService ,
Func < IPollingUpdateTaskManager > viewUpdateManager ,
2021-06-26 20:57:55 +02:00
ISmartDevice smartDevice ,
2021-05-13 20:03:07 +02:00
IViewService viewService ,
IBikesViewModel bikesViewModel ,
IUser activeUser ) : base (
selectedBike ,
AppResources . ActionRequest , // Copri text: "Rad reservieren"
true , // Show copri button to enable reserving and opening
isConnectedDelegate ,
connectorFactory ,
geolocation ,
lockService ,
viewUpdateManager ,
2021-06-26 20:57:55 +02:00
smartDevice ,
2021-05-13 20:03:07 +02:00
viewService ,
bikesViewModel ,
activeUser )
{
LockitButtonText = GetType ( ) . Name ;
IsLockitButtonVisible = false ; // If bike is not reserved/ booked app can not connect to lock
}
/// <summary> Gets the bike state. </summary>
public override InUseStateEnum State = > InUseStateEnum . Disposable ;
/// <summary>Reserve bike and connect to lock.</summary>
2021-06-26 20:57:55 +02:00
public async Task < IRequestHandler > HandleRequestOption1 ( ) = > await ReserverBookAndOpen ( ) ;
public async Task < IRequestHandler > HandleRequestOption2 ( ) = > await UnsupportedRequest ( ) ;
/// <summary>Reserve bike and connect to lock.</summary>
public async Task < IRequestHandler > ReserverBookAndOpen ( )
2021-05-13 20:03:07 +02:00
{
BikesViewModel . IsIdle = false ;
// Ask whether to really book bike?
var alertResult = await ViewService . DisplayAlert (
string . Empty ,
2021-06-26 20:57:55 +02:00
string . Format ( AppResources . QuestionReserveBike , SelectedBike . GetFullDisplayName ( ) , StateRequestedInfo . MaximumReserveTime . Minutes ) ,
2021-05-13 20:03:07 +02:00
AppResources . MessageAnswerYes ,
AppResources . MessageAnswerNo ) ;
if ( alertResult = = false )
{
// User aborted booking process
Log . ForContext < DisposableDisconnected > ( ) . Information ( "User selected availalbe bike {bike} in order to reserve but action was canceled." , SelectedBike ) ;
BikesViewModel . IsIdle = true ;
return this ;
}
// Lock list to avoid multiple taps while copri action is pending.
Log . ForContext < DisposableDisconnected > ( ) . Information ( "Request to book and open lock for bike {bike} detected." , SelectedBike ) ;
BikesViewModel . ActionText = AppResources . ActivityTextOneMomentPlease ;
// Stop polling before requesting bike.
await ViewUpdateManager ( ) . StopUpdatePeridically ( ) ;
BikesViewModel . ActionText = AppResources . ActivityTextReservingBike ;
IsConnected = IsConnectedDelegate ( ) ;
try
{
await ConnectorFactory ( IsConnected ) . Command . DoReserve ( SelectedBike ) ;
}
catch ( Exception exception )
{
BikesViewModel . ActionText = string . Empty ;
if ( exception is BookingDeclinedException )
{
// Too many bikes booked.
Log . ForContext < DisposableDisconnected > ( ) . Information ( "Request declined because maximum count of bikes {l_oException.MaxBikesCount} already requested/ booked." , ( exception as BookingDeclinedException ) . MaxBikesCount ) ;
await ViewService . DisplayAlert (
AppResources . MessageTitleHint ,
string . Format ( AppResources . MessageReservationBikeErrorTooManyReservationsRentals , SelectedBike . Id , ( exception as BookingDeclinedException ) . MaxBikesCount ) ,
AppResources . MessageAnswerOk ) ;
}
else if ( exception is WebConnectFailureException )
{
// Copri server is not reachable.
Log . ForContext < DisposableDisconnected > ( ) . Information ( "User selected availalbe bike {bike} but reserving failed (Copri server not reachable)." , SelectedBike ) ;
await ViewService . DisplayAlert (
"Verbingungsfehler beim Reservieren des Rads!" ,
string . Format ( "{0}\r\n{1}" , exception . Message , WebConnectFailureException . GetHintToPossibleExceptionsReasons ) ,
"OK" ) ;
}
else
{
Log . ForContext < DisposableDisconnected > ( ) . Error ( "User selected availalbe bike {bike} but reserving failed. {@l_oException}" , SelectedBike , exception ) ;
await ViewService . DisplayAlert (
"Fehler beim Reservieren des Rads!" ,
exception . Message ,
"OK" ) ;
}
// Restart polling again.
BikesViewModel . ActionText = AppResources . ActivityTextStartingUpdater ;
await ViewUpdateManager ( ) . StartUpdateAyncPeridically ( ) ;
BikesViewModel . ActionText = string . Empty ;
BikesViewModel . IsIdle = true ;
return this ;
}
// Search for lock.
LockInfoTdo result = null ;
BikesViewModel . ActionText = AppResources . ActivityTextSearchingLock ;
try
{
result = await LockService . ConnectAsync (
new LockInfoAuthTdo . Builder { Id = SelectedBike . LockInfo . Id , Guid = SelectedBike . LockInfo . Guid , K_seed = SelectedBike . LockInfo . Seed , K_u = SelectedBike . LockInfo . UserKey } . Build ( ) ,
LockService . TimeOut . GetSingleConnect ( 1 ) ) ;
}
catch ( Exception exception )
{
// Do not display any messages here, because search is implicit.
if ( exception is OutOfReachException )
{
Log . ForContext < DisposableDisconnected > ( ) . Debug ( "Lock state can not be retrieved, lock is out of reach. {Exception}" , exception ) ;
BikesViewModel . ActionText = "Schloss außerhalb Reichweite" ;
}
else
{
Log . ForContext < DisposableDisconnected > ( ) . Error ( "Lock state can not be retrieved. {Exception}" , exception ) ;
BikesViewModel . ActionText = "Schloss nicht gefunden" ;
}
// Restart polling again.
BikesViewModel . ActionText = AppResources . ActivityTextStartingUpdater ;
await ViewUpdateManager ( ) . StartUpdateAyncPeridically ( ) ;
BikesViewModel . ActionText = string . Empty ;
BikesViewModel . IsIdle = true ;
2021-06-26 20:57:55 +02:00
return RequestHandlerFactory . Create ( SelectedBike , IsConnectedDelegate , ConnectorFactory , Geolocation , LockService , ViewUpdateManager , SmartDevice , ViewService , BikesViewModel , ActiveUser ) ;
2021-05-13 20:03:07 +02:00
}
SelectedBike . LockInfo . State = result ? . State ? . GetLockingState ( ) ? ? LockingState . Disconnected ;
if ( SelectedBike . LockInfo . State = = LockingState . Disconnected )
{
// Do not display any messages here, because search is implicit.
Log . ForContext < DisposableDisconnected > ( ) . Information ( "Lock for bike {bike} not found." , SelectedBike ) ;
// Restart polling again.
BikesViewModel . ActionText = AppResources . ActivityTextStartingUpdater ;
await ViewUpdateManager ( ) . StartUpdateAyncPeridically ( ) ;
BikesViewModel . ActionText = string . Empty ;
BikesViewModel . IsIdle = true ;
2021-06-26 20:57:55 +02:00
return RequestHandlerFactory . Create ( SelectedBike , IsConnectedDelegate , ConnectorFactory , Geolocation , LockService , ViewUpdateManager , SmartDevice , ViewService , BikesViewModel , ActiveUser ) ;
2021-05-13 20:03:07 +02:00
}
SelectedBike . LockInfo . Guid = result ? . Guid ? ? new Guid ( ) ;
Log . ForContext < DisposableDisconnected > ( ) . Information ( "Lock found {bike} successfully." , SelectedBike ) ;
BikesViewModel . ActionText = string . Empty ;
// Ask whether to really book bike?
alertResult = await ViewService . DisplayAlert (
string . Empty ,
2021-08-28 10:04:10 +02:00
string . Format ( AppResources . QuestionOpenLockAndBookBike , SelectedBike . GetFullDisplayName ( ) ) ,
2021-05-13 20:03:07 +02:00
AppResources . MessageAnswerYes ,
AppResources . MessageAnswerNo ) ;
if ( alertResult = = false )
{
// User aborted booking process
Log . ForContext < DisposableDisconnected > ( ) . Information ( "User selected recently requested bike {bike} in order to reserve but did deny to book bike." , SelectedBike ) ;
// Disconnect lock.
BikesViewModel . ActionText = AppResources . ActivityTextDisconnectingLock ;
try
{
SelectedBike . LockInfo . State = await LockService . DisconnectAsync ( SelectedBike . LockInfo . Id , SelectedBike . LockInfo . Guid ) ;
}
catch ( Exception exception )
{
Log . ForContext < DisposableDisconnected > ( ) . Error ( "Lock can not be disconnected. {Exception}" , exception ) ;
BikesViewModel . ActionText = AppResources . ActivityTextErrorDisconnect ;
}
// Restart polling again.
BikesViewModel . ActionText = AppResources . ActivityTextStartingUpdater ;
await ViewUpdateManager ( ) . StartUpdateAyncPeridically ( ) ;
BikesViewModel . ActionText = string . Empty ;
BikesViewModel . IsIdle = true ;
2021-06-26 20:57:55 +02:00
return RequestHandlerFactory . Create ( SelectedBike , IsConnectedDelegate , ConnectorFactory , Geolocation , LockService , ViewUpdateManager , SmartDevice , ViewService , BikesViewModel , ActiveUser ) ;
2021-05-13 20:03:07 +02:00
}
Log . ForContext < DisposableDisconnected > ( ) . Information ( "User selected recently requested bike {bike} in order to book." , SelectedBike ) ;
// Book bike prior to opening lock.
BikesViewModel . ActionText = AppResources . ActivityTextRentingBike ;
IsConnected = IsConnectedDelegate ( ) ;
try
{
await ConnectorFactory ( IsConnected ) . Command . DoBook ( SelectedBike ) ;
}
catch ( Exception l_oException )
{
BikesViewModel . ActionText = string . Empty ;
if ( l_oException is WebConnectFailureException )
{
// Copri server is not reachable.
Log . ForContext < DisposableDisconnected > ( ) . Information ( "User selected recently 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 < DisposableDisconnected > ( ) . Error ( "User selected recently 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 . IsIdle = true ; // Unlock GUI
2021-06-26 20:57:55 +02:00
return RequestHandlerFactory . Create ( SelectedBike , IsConnectedDelegate , ConnectorFactory , Geolocation , LockService , ViewUpdateManager , SmartDevice , ViewService , BikesViewModel , ActiveUser ) ;
2021-05-13 20:03:07 +02:00
}
// Unlock bike.
BikesViewModel . ActionText = AppResources . ActivityTextOpeningLock ;
try
{
SelectedBike . LockInfo . State = ( await LockService [ SelectedBike . LockInfo . Id ] . OpenAsync ( ) ) ? . GetLockingState ( ) ? ? LockingState . Disconnected ;
}
catch ( Exception exception )
{
BikesViewModel . ActionText = string . Empty ;
if ( exception is OutOfReachException )
{
Log . ForContext < DisposableDisconnected > ( ) . Debug ( "Lock can not be opened. {Exception}" , exception ) ;
await ViewService . DisplayAlert (
AppResources . ErrorOpenLockTitle ,
AppResources . ErrorOpenLockOutOfReadMessage ,
"OK" ) ;
}
2021-06-26 20:57:55 +02:00
else if ( exception is CouldntOpenBoldIsBlockedException )
2021-05-13 20:03:07 +02:00
{
Log . ForContext < DisposableDisconnected > ( ) . Debug ( "Lock can not be opened. Bold is blocked. {Exception}" , exception ) ;
await ViewService . DisplayAlert (
AppResources . ErrorOpenLockTitle ,
2021-06-26 20:57:55 +02:00
AppResources . ErrorOpenLockBoldBlockedMessage ,
"OK" ) ;
}
else if ( exception is CouldntOpenBoldWasBlockedException )
{
2021-08-28 10:04:10 +02:00
Log . ForContext < DisposableDisconnected > ( ) . Debug ( "Lock can not be opened. Bold was or is blocked. {Exception}" , exception ) ;
2021-06-26 20:57:55 +02:00
await ViewService . DisplayAlert (
AppResources . ErrorOpenLockStillOpenTitle ,
AppResources . ErrorOpenLockBoldWasBlockedMessage ,
2021-05-13 20:03:07 +02:00
"OK" ) ;
}
else if ( exception is CouldntOpenInconsistentStateExecption inconsistentState
& & inconsistentState . State = = LockingState . Closed )
{
Log . ForContext < DisposableDisconnected > ( ) . Debug ( "Lock can not be opened. lock reports state closed. {Exception}" , exception ) ;
await ViewService . DisplayAlert (
AppResources . ErrorOpenLockTitle ,
AppResources . ErrorOpenLockStillClosedMessage ,
"OK" ) ;
}
else
{
Log . ForContext < DisposableDisconnected > ( ) . Error ( "Lock can not be opened. {Exception}" , exception ) ;
await ViewService . DisplayAlert (
AppResources . ErrorOpenLockTitle ,
exception . Message ,
"OK" ) ;
}
SelectedBike . LockInfo . State = exception is StateAwareException stateAwareException
? stateAwareException . State
: LockingState . Disconnected ;
BikesViewModel . ActionText = AppResources . ActivityTextStartingUpdater ;
await ViewUpdateManager ( ) . StartUpdateAyncPeridically ( ) ; // Restart polling again.
BikesViewModel . ActionText = string . Empty ;
BikesViewModel . IsIdle = true ;
2021-06-26 20:57:55 +02:00
return RequestHandlerFactory . Create ( SelectedBike , IsConnectedDelegate , ConnectorFactory , Geolocation , LockService , ViewUpdateManager , SmartDevice , ViewService , BikesViewModel , ActiveUser ) ;
2021-05-13 20:03:07 +02:00
}
if ( SelectedBike . LockInfo . State ! = LockingState . Open )
{
// Opening lock failed.
BikesViewModel . ActionText = AppResources . ActivityTextStartingUpdater ;
await ViewUpdateManager ( ) . StartUpdateAyncPeridically ( ) ; // Restart polling again.
BikesViewModel . ActionText = "" ;
BikesViewModel . IsIdle = true ; // Unlock GUI
2021-06-26 20:57:55 +02:00
return RequestHandlerFactory . Create ( SelectedBike , IsConnectedDelegate , ConnectorFactory , Geolocation , LockService , ViewUpdateManager , SmartDevice , ViewService , BikesViewModel , ActiveUser ) ;
2021-05-13 20:03:07 +02:00
}
BikesViewModel . ActionText = AppResources . ActivityTextReadingChargingLevel ;
try
{
2021-06-26 20:57:55 +02:00
SelectedBike . LockInfo . BatteryPercentage = await LockService [ SelectedBike . LockInfo . Id ] . GetBatteryPercentageAsync ( ) ;
2021-05-13 20:03:07 +02:00
}
catch ( Exception exception )
{
if ( exception is OutOfReachException )
{
Log . ForContext < DisposableDisconnected > ( ) . Debug ( "Akkustate can not be read, bike out of range. {Exception}" , exception ) ;
BikesViewModel . ActionText = AppResources . ActivityTextErrorReadingChargingLevelOutOfReach ;
}
else
{
Log . ForContext < DisposableDisconnected > ( ) . Error ( "Akkustate can not be read. {Exception}" , exception ) ;
BikesViewModel . ActionText = AppResources . ActivityTextErrorReadingChargingLevelGeneral ;
}
}
// Lock list to avoid multiple taps while copri action is pending.
BikesViewModel . ActionText = AppResources . ActivityTextStartingUpdatingLockingState ;
IsConnected = IsConnectedDelegate ( ) ;
try
{
await ConnectorFactory ( IsConnected ) . Command . UpdateLockingStateAsync ( SelectedBike ) ;
}
catch ( Exception exception )
{
if ( exception is WebConnectFailureException )
{
// Copri server is not reachable.
Log . ForContext < DisposableDisconnected > ( ) . 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 < DisposableDisconnected > ( ) . Information ( "User locked bike {bike} in order to pause ride but updating failed. {response}." , SelectedBike , copriException . Response ) ;
BikesViewModel . ActionText = AppResources . ActivityTextErrorStatusUpdateingLockstate ;
}
else
{
Log . ForContext < DisposableDisconnected > ( ) . Error ( "User locked bike {bike} in order to pause ride but updating failed . {@l_oException}" , SelectedBike . Id , exception ) ;
BikesViewModel . ActionText = AppResources . ActivityTextErrorConnectionUpdateingLockstate ;
}
}
Log . ForContext < DisposableDisconnected > ( ) . 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
2021-06-26 20:57:55 +02:00
return RequestHandlerFactory . Create ( SelectedBike , IsConnectedDelegate , ConnectorFactory , Geolocation , LockService , ViewUpdateManager , SmartDevice , ViewService , BikesViewModel , ActiveUser ) ;
2021-05-13 20:03:07 +02:00
}
2021-06-26 20:57:55 +02:00
/// <summary> Requst is not supported, button should be disabled. </summary>
/// <returns></returns>
public async Task < IRequestHandler > UnsupportedRequest ( )
2021-05-13 20:03:07 +02:00
{
2021-06-26 20:57:55 +02:00
Log . ForContext < DisposableDisconnected > ( ) . Error ( "Click of unsupported button click detected." ) ;
return await Task . FromResult < IRequestHandler > ( this ) ;
2021-05-13 20:03:07 +02:00
}
}
}