using System;
using System.Runtime.Serialization;
using Newtonsoft.Json;
namespace TINK.Model.State
{
///
/// Manages state reserved.
///
[DataContract]
public sealed class StateRequestedInfo : BaseState, IBaseState, INotAvailableState
{
// Maximum time while reserving request is kept.
public static readonly TimeSpan MaximumReserveTime = new TimeSpan(0, 15, 0); // 15 mins
// Reference to date time provider.
private Func _DateTimeNowProvider;
///
/// Prevents an invalid instance to be created.
/// Used by serializer only.
///
private StateRequestedInfo() : base(InUseStateEnum.Reserved)
{
// Is called in context of JSON deserialization.
_DateTimeNowProvider = () => DateTime.Now;
}
///
/// Reservation performed with other device/ before start of app.
/// Date time info when bike was reserved has been received from webserver.
///
/// Time span which holds duration how long bike still will be reserved.
[JsonConstructor]
private StateRequestedInfo(
InUseStateEnum Value,
DateTime From,
string MailAddress,
string Code) : this(() => DateTime.Now, From, MailAddress, Code)
{
}
///
/// Reservation performed with other device/ before start of app.
/// Date time info when bike was reserved has been received from webserver.
///
///
/// Used to to provide current date time information for potential calls of .
/// Not used to calculate remaining time because this duration whould always be shorter as the one received from webserver.
///
public StateRequestedInfo(
Func dateTimeNowProvider,
DateTime from,
string mailAddress,
string code) : base(InUseStateEnum.Reserved)
{
_DateTimeNowProvider = dateTimeNowProvider ?? (() => DateTime.Now);
From = from;
MailAddress = mailAddress;
Code = code;
}
///
/// Tries update
///
/// True if reservation span has not exeeded and state remains reserved, false otherwise.
/// Implement logging of time stamps.
public bool GetIsStillReserved(out TimeSpan? p_oRemainingTime)
{
var l_oTimeReserved = _DateTimeNowProvider().Subtract(From);
if (l_oTimeReserved > MaximumReserveTime)
{
// Reservation has elapsed. To not update remaining time.
p_oRemainingTime = null;
return false;
}
p_oRemainingTime = MaximumReserveTime - l_oTimeReserved;
return true;
}
///
/// State reserved.
/// Setter exists only for serialization purposes.
///
public override InUseStateEnum Value
{
get
{
return InUseStateEnum.Reserved;
}
}
///
/// Date time when bike was reserved.
///
[DataMember]
public DateTime From { get; }
///
/// Mail address of user who reserved the bike.
///
[DataMember]
public string MailAddress { get; }
///
/// Booking code.
///
[DataMember]
public string Code { get; }
}
}