using System.Text.RegularExpressions;
namespace ShareeBike.Repository.Exception
{
public class NotAtStationException : InvalidResponseException
{
public const string RETURNBIKE_FAILURE_STATUS_MESSAGE_CODE = "FAILURE 2178:";
/// COPRI response status regular expression to extract detail information.
public const string RETURNBIKE_FAILURE_STATUS_MESSAGE_UPPERCASE = "(BIKE [A-Za-z0-9_]+ OUT OF GEO FENCING\\. )([0-9]+)( METER DISTANCE TO NEXT STATION )([A-Za-z0-9_]+)";
/// Prevents invalid use of exception.
private NotAtStationException() : base(typeof(NotAtStationException).Name)
{
}
public static bool IsNotAtStation(string responseState, out NotAtStationException exception)
{
// Check if there are too many bikes requested/ booked.
var response = responseState.Trim().ToUpper();
if (!response.StartsWith(RETURNBIKE_FAILURE_STATUS_MESSAGE_CODE))
{
exception = null;
return false;
}
var match = Regex.Match(
responseState.ToUpper(),
RETURNBIKE_FAILURE_STATUS_MESSAGE_UPPERCASE);
if (match.Groups.Count != 5
|| !int.TryParse(match.Groups[2].ToString(), out int meters))
{
exception = new NotAtStationException();
return true;
}
exception = new NotAtStationException {
Distance = meters,
StationNr = match.Groups[4].ToString()
};
return true;
}
/// Holds the distance to next station.
public int? Distance { get; private set; } = null;
/// Holds the id of next station.
public string StationNr { get; private set; } = string.Empty;
}
}