namespace StockSharp.Algo.Import;
///
/// Importing field description.
///
public abstract class FieldMapping : NotifiableObject, IPersistable, ICloneable
{
private FastDateTimeParser _dateParser;
private FastTimeSpanParser _timeParser;
private Func _dateConverter;
private readonly HashSet _enumNames = new(StringComparer.InvariantCultureIgnoreCase);
///
/// Display name.
///
protected readonly Func GetDisplayName;
///
/// Description.
///
protected readonly Func GetDescription;
///
/// Initializes a new instance of the .
///
/// Name.
/// Display name.
/// Description.
/// Field type.
protected FieldMapping(string name, Func getDisplayName, Func getDescription, Type type)
{
Type = type ?? throw new ArgumentNullException(nameof(type));
Name = name.ThrowIfEmpty(nameof(name));
GetDisplayName = getDisplayName ?? throw new ArgumentNullException(nameof(getDisplayName));
GetDescription = getDescription ?? throw new ArgumentNullException(nameof(getDescription));
IsEnabled = true;
if (Type.IsDateTime())
Format = "yyyyMMdd";
else if (Type == typeof(TimeSpan))
Format = "hh:mm:ss";
if (Type.IsEnum)
_enumNames.AddRange(Type.GetNames());
LocalizedStrings.ActiveLanguageChanged += OnActiveLanguageChanged;
}
private void OnActiveLanguageChanged()
{
NotifyChanged(nameof(DisplayName));
NotifyChanged(nameof(Description));
}
///
/// Name.
///
public string Name { get; private set; }
///
/// Is field extended.
///
public bool IsExtended { get; set; }
///
/// Display name.
///
public string DisplayName => GetDisplayName();
///
/// Description.
///
public string Description => GetDescription().IsEmpty(GetDisplayName());
///
/// Date format.
///
public string Format { get; set; }
///
/// Field type.
///
public Type Type { get; }
///
/// Is field required.
///
public bool IsRequired { get; set; }
///
/// Is field enabled.
///
public bool IsEnabled
{
get => Order != null;
set
{
if (IsEnabled == value)
return;
if (value)
Order ??= 0;
else
Order = null;
NotifyChanged(nameof(IsEnabled));
NotifyChanged(nameof(Order));
}
}
private int? _order;
///
/// Field order.
///
public int? Order
{
get => _order;
set
{
if (Order == value)
return;
if (value < 0)
throw new ArgumentOutOfRangeException(nameof(value));
_order = value;
IsEnabled = value != null;
NotifyChanged(nameof(IsEnabled));
NotifyChanged(nameof(Order));
}
}
private IEnumerable _values = [];
///
/// Mapping values.
///
public IEnumerable Values
{
get => _values;
set => _values = value ?? throw new ArgumentNullException(nameof(value));
}
///
/// Default value.
///
public string DefaultValue { get; set; }
///
/// Zero as .
///
public bool ZeroAsNull { get; set; }
///
/// Multiple field's instancies allowed.
///
public bool IsMultiple => IsAdapter;
///
/// required.
///
public bool IsAdapter { get; set; }
///
/// Adapter.
///
public Type AdapterType { get; set; }
///
/// Load settings.
///
/// Settings storage.
public void Load(SettingsStorage storage)
{
Name = storage.GetValue(nameof(Name));
IsExtended = storage.GetValue(nameof(IsExtended));
Values = [.. storage.GetValue(nameof(Values)).Select(s => s.Load())];
DefaultValue = storage.GetValue(nameof(DefaultValue));
Format = storage.GetValue(nameof(Format));
ZeroAsNull = storage.GetValue(nameof(ZeroAsNull));
//IsEnabled = storage.GetValue(nameof(IsEnabled), IsEnabled);
if (storage.ContainsKey(nameof(IsEnabled)))
IsEnabled = storage.GetValue(nameof(IsEnabled));
else
Order = storage.GetValue(nameof(Order));
IsAdapter = storage.GetValue(nameof(IsAdapter), IsAdapter);
AdapterType = storage.GetValue(nameof(AdapterType)).To();
}
void IPersistable.Save(SettingsStorage storage)
{
storage.SetValue(nameof(Name), Name);
storage.SetValue(nameof(IsExtended), IsExtended);
storage.SetValue(nameof(Values), Values.Select(v => v.Save()).ToArray());
storage.SetValue(nameof(DefaultValue), DefaultValue);
storage.SetValue(nameof(Format), Format);
//storage.SetValue(nameof(IsEnabled), IsEnabled);
storage.SetValue(nameof(Order), Order);
storage.SetValue(nameof(ZeroAsNull), ZeroAsNull);
storage.SetValue(nameof(IsAdapter), IsAdapter);
storage.SetValue(nameof(AdapterType), AdapterType.To());
}
///
/// Apply value.
///
/// Instance.
/// Field value.
public void ApplyFileValue(object instance, string value)
{
if (value.IsEmpty())
{
ApplyDefaultValue(instance);
return;
}
if (Values.Any())
{
var v = Values.FirstOrDefault(vl => vl.ValueFile.EqualsIgnoreCase(value));
if (v != null)
{
ApplyValue(instance, v.ValueStockSharp);
return;
}
}
if (_enumNames.Contains(value))
{
ApplyValue(instance, value.To(Type));
return;
}
ApplyValue(instance, value);
}
///
/// Apply default value.
///
/// Instance.
public void ApplyDefaultValue(object instance)
{
ApplyValue(instance, DefaultValue);
}
private void EnsureDateConverter()
{
if(_dateConverter != null)
return;
object fastParserConverter(string str)
{
if (Type == typeof(DateTimeOffset))
{
var dto = _dateParser.ParseDto(str);
if (dto.Offset == default)
{
var tz = Scope.Current?.Value;
if (tz != null)
dto = dto.UtcDateTime.ApplyTimeZone(tz);
}
return dto;
}
return _dateParser.Parse(str);
}
Func toObj = Type == typeof(DateTimeOffset) ? dto => dto : dto => dto.DateTime;
switch (Format.ToLowerInvariant())
{
case "timestamp":
case "unix":
_dateConverter = str => toObj(DateTimeOffset.FromUnixTimeSeconds(long.Parse(str)));
break;
case "timestamp_milli":
case "unixmls":
case "unix_mls":
_dateConverter = str => toObj(DateTimeOffset.FromUnixTimeMilliseconds(long.Parse(str)));
break;
case "timestamp_micro":
_dateConverter = str => toObj(new DateTimeOffset(long.Parse(str).MicrosecondsToTicks(), TimeSpan.Zero));
break;
case "timestamp_nano":
_dateConverter = str => toObj(new DateTimeOffset(long.Parse(str).NanosecondsToTicks(), TimeSpan.Zero));
break;
default:
_dateParser = new FastDateTimeParser(Format);
_dateConverter = fastParserConverter;
break;
}
}
private void ApplyValue(object instance, object value)
{
if (Type == typeof(decimal))
{
if (value is string str)
{
if (str.ContainsIgnoreCase("e")) // exponential notation
value = str.To();
else
{
str = str.Replace(',', '.').RemoveSpaces().ReplaceWhiteSpaces().Trim();
if (str.IsEmpty())
return;
value = str;
}
}
}
else if (Type.IsDateTime())
{
if (value is string str)
{
EnsureDateConverter();
value = _dateConverter(str);
}
}
else if (Type == typeof(TimeSpan))
{
if (value is string str)
{
_timeParser ??= new FastTimeSpanParser(Format);
value = _timeParser.Parse(str);
}
}
if (value != null)
{
value = value.To(Type);
if (ZeroAsNull && Type.IsNumeric() && value.To() == 0)
return;
OnApply(instance, value);
}
}
///
/// Apply value.
///
/// Instance.
/// Field value.
protected abstract void OnApply(object instance, object value);
///
public override string ToString() => Name;
///
public abstract object Clone();
///
/// Reset state.
///
public void Reset()
{
_dateParser = null;
_timeParser = null;
_dateConverter = null;
}
///
/// Get instance or clone dependent on .
///
/// Field.
public FieldMapping GetOrClone()
{
return IsMultiple ? (FieldMapping)Clone() : this;
}
}
///
/// Importing field description.
///
/// Type, containing the field.
/// Field value type.
public class FieldMapping : FieldMapping
{
private readonly Action _apply;
///
/// Initializes a new instance of the .
///
/// Name.
/// Display name.
/// Description.
/// Apply field value action.
public FieldMapping(string name, Func getDisplayName, Func getDescription, Action apply)
: this(name, getDisplayName, getDescription, typeof(TValue), apply)
{
}
///
/// Initializes a new instance of the .
///
/// Name.
/// Display name.
/// Description.
/// Field type.
/// Apply field value action.
public FieldMapping(string name, Func getDisplayName, Func getDescription, Type type, Action apply)
: base(name, getDisplayName, getDescription, type)
{
_apply = apply ?? throw new ArgumentNullException(nameof(apply));
}
///
protected override void OnApply(object instance, object value)
{
_apply((TInstance)instance, (TValue)value);
}
///
public override object Clone()
{
var clone = new FieldMapping(Name, GetDisplayName, GetDescription, _apply);
clone.Load(this.Save());
return clone;
}
}