using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text.RegularExpressions;
namespace Raytheon.Units
{
///
/// Contains info related to a unit: to parse, print, and convert values
///
internal class UnitInfo
{
public UnitInfo( List abbreviation,
Func conversionMethod,
MethodInfo propertyGetter )
{
Abbreviation = abbreviation;
ConversionMethod = conversionMethod;
PropertyGetter = propertyGetter;
}
///
/// standard text abbreviation for this unit
///
public List Abbreviation { get; private set; }
///
/// method for converting string to this unit
///
public Func ConversionMethod { get; private set; }
///
/// get method for the property associated with this unit
///
public MethodInfo PropertyGetter { get; set; }
}
internal class Common
{
///
/// Converts a string that represents a number with a unit to the actual
/// unit type.
///
/// Enumeration of the Unit abbreviation
/// The actual unit type, i.e Current
/// String that represents a unit value, i.e 1.23 Amps
/// Look up table for how to convert the units
///
/// The converted number to the correct unit type. If unable to parse, will return the first
/// with a value of
///
public static T Parse( string s, IDictionary> unitInfo )
{
const string FloatingPointPattern = @"([-+]?[0-9]+(\.[0-9]+)?([Ee][+-][0-9]+)?)";
const string AbbreviationPattern = @"([\w/\^]*)";
string pattern = FloatingPointPattern + @"\s*" + AbbreviationPattern;
Regex regEx = new Regex( pattern );
Match match = regEx.Match( s );
if(!match.Success || match.Groups.Count == 0 )
{
throw new FormatException( $"UUnknown value : {s}" );
}
string abbreviation = match.Groups[match.Groups.Count - 1].Value;
IEnumerable> x = unitInfo.Where( kvp => kvp.Value.Abbreviation.Contains( abbreviation, StringComparer.CurrentCultureIgnoreCase ) )
.Select( kvp => kvp.Value );
// abbreviation not found?
if ( x.Count( ) == 0 )
{
throw new FormatException( $"Unknown units: '{abbreviation}'" );
}
double value = double.Parse( match.Groups[1].Value );
return x.First( ).ConversionMethod( value );
}
}
}