using Elsa.Expressions.Contracts;
using Elsa.Expressions.Extensions;
using Elsa.Expressions.Helpers;
using Elsa.Extensions;
using Elsa.Workflows.Core.Memory;
using Elsa.Workflows.Core.Models;
namespace Elsa.Workflows.Management.Mappers;
///
/// Maps s to s and vice versa.
///
public class VariableDefinitionMapper
{
private readonly IWellKnownTypeRegistry _wellKnownTypeRegistry;
///
/// Constructor.
///
public VariableDefinitionMapper(IWellKnownTypeRegistry wellKnownTypeRegistry)
{
_wellKnownTypeRegistry = wellKnownTypeRegistry;
}
///
/// Maps a to a .
///
public Variable? Map(VariableDefinition source)
{
if (!_wellKnownTypeRegistry.TryGetTypeOrDefault(source.TypeName, out var type))
return null;
var valueType = source.IsArray ? typeof(ICollection<>).MakeGenericType(type) : type;
var variableGenericType = typeof(Variable<>).MakeGenericType(valueType);
var variable = (Variable)Activator.CreateInstance(variableGenericType)!;
if(!string.IsNullOrEmpty(source.Id))
variable.Id = source.Id;
variable.Name = source.Name;
variable.Value = source.Value.ConvertTo(valueType);
variable.StorageDriverType = !string.IsNullOrEmpty(source.StorageDriverTypeName) ? Type.GetType(source.StorageDriverTypeName) : default;
return variable;
}
///
/// Maps a list of s to a list of .
///
public IEnumerable Map(IEnumerable? source) =>
source?
.Select(Map)
.Where(x => x != null)
.Select(x => x!)
?? Enumerable.Empty();
///
/// Maps a to a .
///
public VariableDefinition Map(Variable source)
{
var variableType = source.GetType();
var valueType = variableType.IsConstructedGenericType ? variableType.GetGenericArguments().FirstOrDefault() ?? typeof(object) : typeof(object);
var isArray = valueType.IsCollectionType();
var elementValueType = isArray ? valueType.GenericTypeArguments[0] : valueType;
var value = source.Value;
var valueTypeAlias = _wellKnownTypeRegistry.GetAliasOrDefault(elementValueType);
var storageDriverTypeName = source.StorageDriverType?.GetSimpleAssemblyQualifiedName();
var serializedValue = value.Format();
return new VariableDefinition(source.Id, source.Name, valueTypeAlias, isArray, serializedValue, storageDriverTypeName);
}
///
/// Maps a list of s to a list of s.
///
public IEnumerable Map(IEnumerable? source) => source?.Select(Map) ?? Enumerable.Empty();
}