using Serilog;
using System;
using System.ComponentModel;
using System.Text.RegularExpressions;
#if !USEFLYOUT
using System.Threading.Tasks;
#endif
using TINK.Model.Connector;
using TINK.Model.Device;
using TINK.Model.State;
using TINK.Model.User;
using TINK.MultilingualResources;
using TINK.View;
using Xamarin.Forms;
using BikeInfoMutable = TINK.Model.Bike.BC.BikeInfoMutable;
namespace TINK.ViewModel.Bikes.Bike
{
///
/// Defines the type of BikesViewModel child items, i.e. BikesViewModel derives from ObservableCollection<BikeViewModelBase>.
/// Holds references to
/// - connection state services
/// - copri service
/// - view service
///
public abstract class BikeViewModelBase
{
///
/// Time format for text "Gebucht seit".
///
public const string TIMEFORMAT = "dd. MMMM HH:mm";
/// Provides info about the smart device (phone, tablet, ...).
protected ISmartDevice SmartDevice;
///
/// Reference on view service to show modal notifications and to perform navigation.
///
protected IViewService ViewService { get; }
/// Provides a connect orobject.
protected Func ConnectorFactory { get; }
/// Delegate to retrieve connected state.
protected Func IsConnectedDelegate { get; }
/// Removes bike from bikes view model.
protected Action BikeRemoveDelegate { get; }
/// Object to manage update of view model objects from Copri.
public Func ViewUpdateManager { get; }
///
/// Holds the bike to display.
///
protected BikeInfoMutable bike;
/// Reference on the user
protected IUser ActiveUser { get; }
///
/// Provides context related info.
///
private IInUseStateInfoProvider StateInfoProvider { get; }
/// View model to be used for progress report and unlocking/ locking view.
protected IBikesViewModel BikesViewModel { get; }
/// Delegate to open browser.
private Action OpenUrlInBrowser;
///
/// Notifies GUI about changes.
///
public abstract event PropertyChangedEventHandler PropertyChanged;
///
/// Notfies childs about changed bike state.
///
public abstract void OnSelectedBikeStateChanged();
/// Raises events in order to update GUI.
public abstract void RaisePropertyChanged(object sender, PropertyChangedEventArgs eventArgs);
///
/// Constructs a bike view model object.
///
/// Provides info about the smart device (phone, tablet, ...).
/// Bike to be displayed.
/// Object holding logged in user or an empty user object.
/// Provides in use state information.
/// View model to be used for progress report and unlocking/ locking view.
/// Delegate to open browser.
public BikeViewModelBase(
Func isConnectedDelegate,
Func connectorFactory,
Action bikeRemoveDelegate,
Func viewUpdateManager,
ISmartDevice smartDevice,
IViewService viewService,
BikeInfoMutable selectedBike,
IUser activeUser,
IInUseStateInfoProvider stateInfoProvider,
IBikesViewModel bikesViewModel,
Action openUrlInBrowser)
{
IsConnectedDelegate = isConnectedDelegate;
ConnectorFactory = connectorFactory;
BikeRemoveDelegate = bikeRemoveDelegate;
ViewUpdateManager = viewUpdateManager;
SmartDevice = smartDevice;
ViewService = viewService;
bike = selectedBike
?? throw new ArgumentException(string.Format("Can not construct {0}- object, bike object is null.", typeof(BikeViewModelBase)));
ActiveUser = activeUser
?? throw new ArgumentException(string.Format("Can not construct {0}- object, user object is null.", typeof(BikeViewModelBase)));
StateInfoProvider = stateInfoProvider
?? throw new ArgumentException(string.Format("Can not construct {0}- object, user object is null.", typeof(IInUseStateInfoProvider)));
selectedBike.PropertyChanged +=
(sender, eventargs) => OnSelectedBikePropertyChanged(eventargs.PropertyName);
BikesViewModel = bikesViewModel
?? throw new ArgumentException($"Can not construct {GetType().Name}-object. {nameof(bikesViewModel)} must not be null.");
OpenUrlInBrowser = openUrlInBrowser ?? (url => { Log.ForContext().Error($"No browse service avialble to upen {url}."); });
}
///
/// Handles BikeInfoMutable events.
/// Helper member to raise events. Maps model event change notification to view model events.
///
///
private void OnSelectedBikePropertyChanged(string p_strNameOfProp)
{
if (p_strNameOfProp == nameof(State))
{
OnSelectedBikeStateChanged(); // Notify derived class about change of state.
}
var state = State;
if (LastState != state)
{
RaisePropertyChanged(this, new PropertyChangedEventArgs(nameof(State)));
LastState = state;
}
var stateText = StateText;
if (LastStateText != stateText)
{
RaisePropertyChanged(this, new PropertyChangedEventArgs(nameof(StateText)));
LastStateText = stateText;
}
var stateColor = StateColor;
if (LastStateColor != stateColor)
{
RaisePropertyChanged(this, new PropertyChangedEventArgs(nameof(StateColor)));
LastStateColor = stateColor;
}
}
///
/// Gets the display name of the bike containing of bike id and type of bike..
///
public string Name => bike.GetDisplayName();
///
/// Gets the unique Id of bike or an empty string, if no name is defined to avoid duplicate display of id.
///
public string DisplayId => bike.GetDisplayId();
///
/// Gets the unique Id of bike used by derived model to determine which bike to remove.
///
public string Id=> bike.Id;
///
/// Returns status of a bike as text.
///
/// Log invalid states for diagnose purposes.
public string StateText
{
get
{
switch (bike.State.Value)
{
case InUseStateEnum.Disposable:
return AppResources.StatusTextAvailable;
}
if (!ActiveUser.IsLoggedIn)
{
// Nobody is logged in.
switch (bike.State.Value)
{
case InUseStateEnum.Reserved:
return GetReservedInfo(
bike.State.RemainingTime,
bike.StationId,
null); // Hide reservation code because no one but active user should see code
case InUseStateEnum.Booked:
return GetBookedInfo(
bike.State.From,
bike.StationId,
null); // Hide reservation code because no one but active user should see code
default:
return string.Format("Unbekannter status {0}.", bike.State.Value);
}
}
switch (bike.State.Value)
{
case InUseStateEnum.Reserved:
return bike.State.MailAddress == ActiveUser.Mail
? GetReservedInfo(
bike.State.RemainingTime,
bike.StationId,
bike.State.Code)
: "Fahrrad bereits reserviert durch anderen Nutzer.";
case InUseStateEnum.Booked:
return bike.State.MailAddress == ActiveUser.Mail
? GetBookedInfo(
bike.State.From,
bike.StationId,
bike.State.Code)
: "Fahrrad bereits gebucht durch anderen Nutzer.";
default:
return string.Format("Unbekannter status {0}.", bike.State.Value);
}
}
}
/// Gets the value of property when PropertyChanged was fired.
private string LastStateText { get; set; }
///
/// Gets reserved into display text.
///
/// Log unexpeced states.
///
/// Display text
private string GetReservedInfo(
TimeSpan? p_oRemainingTime,
string p_strStation = null,
string p_strCode = null)
{
return StateInfoProvider.GetReservedInfo(p_oRemainingTime, p_strStation, p_strCode);
}
///
/// Gets booked into display text.
///
/// Log unexpeced states.
///
/// Display text
private string GetBookedInfo(
DateTime? p_oFrom,
string p_strStation = null,
string p_strCode = null)
{
return StateInfoProvider.GetBookedInfo(p_oFrom, p_strStation, p_strCode);
}
///
/// Exposes the bike state.
///
public InUseStateEnum State => bike.State.Value;
/// Gets the value of property when PropertyChanged was fired.
public InUseStateEnum LastState { get; set; }
///
/// Gets the color which visualizes the state of bike in relation to logged in user.
///
public Color StateColor
{
get
{
if (!ActiveUser.IsLoggedIn)
{
return Color.Default;
}
var l_oSelectedBikeState = bike.State;
switch (l_oSelectedBikeState.Value)
{
case InUseStateEnum.Reserved:
return l_oSelectedBikeState.MailAddress == ActiveUser.Mail
? InUseStateEnum.Reserved.GetColor()
: Color.Red; // Bike is reserved by someone else
case InUseStateEnum.Booked:
return l_oSelectedBikeState.MailAddress == ActiveUser.Mail
? InUseStateEnum.Booked.GetColor()
: Color.Red; // Bike is booked by someone else
default:
return Color.Default;
}
}
}
/// Holds description about the tarif.
public TariffDescriptionViewModel TariffDescription => new TariffDescriptionViewModel(bike.TariffDescription);
/// Gets the value of property when PropertyChanged was fired.
public Color LastStateColor { get; set; }
/// Command object to bind login page redirect link to view model.
public System.Windows.Input.ICommand ShowAgbTappedCommand
#if USEFLYOUT
=> new Xamarin.Forms.Command(() => ShowAgbPageAsync());
#else
=> new Xamarin.Forms.Command(async () => await ShowAgbPageAsync());
#endif
/// Opens login page.
#if USEFLYOUT
public void ShowAgbPageAsync()
#else
public async Task ShowAgbPageAsync()
#endif
{
try
{
// Switch to map page
#if USEFLYOUT
var url = GetUrlFirstOrDefault(TariffDescription.OperatorAgb);
if (string.IsNullOrEmpty(url))
{
// No url contained in string.
return;
}
OpenUrlInBrowser(url);
#endif
}
catch (Exception p_oException)
{
Log.Error("An unexpected error occurred opening broser. {@Exception}", p_oException);
return;
}
}
/// Gets first url from text.
/// url to extract text from.
/// Gets first url or an empty string if on url is contained in text.
public static string GetUrlFirstOrDefault(string htmlSource)
{
if (string.IsNullOrEmpty(htmlSource))
return string.Empty;
try
{
var matches = new Regex(@"https://[-a-zA-Z0-9+&@#/%?=~_|!:, .;]*[-a-zA-Z0-9+&@#/%=~_|]").Matches(htmlSource);
return matches.Count > 0
? matches[0].Value
: string.Empty;
} catch (Exception e)
{
Log.ForContext().Error("Extracting URL failed. {Exception}", e);
return string.Empty;
}
}
}
}