1 | using System;
|
---|
2 | using System.Collections.Generic;
|
---|
3 | using System.Linq;
|
---|
4 | using System.Text;
|
---|
5 | using System.Threading.Tasks;
|
---|
6 | using HeuristicLab.Common;
|
---|
7 | using HeuristicLab.Core;
|
---|
8 |
|
---|
9 | namespace HeuristicLab.JsonInterface {
|
---|
10 | public class ConstrainedValueParameterConverter : BaseConverter {
|
---|
11 | public override int Priority => 3;
|
---|
12 |
|
---|
13 | public override bool CanConvertType(Type t) =>
|
---|
14 | t.GetInterfaces().Any(x => x.IsGenericType && x.GetGenericTypeDefinition() == typeof(IConstrainedValueParameter<>));
|
---|
15 |
|
---|
16 | public override void Inject(IItem item, IJsonItem data, IJsonItemConverter root) {
|
---|
17 | StringJsonItem cdata = data as StringJsonItem;
|
---|
18 | IParameter parameter = item as IParameter;
|
---|
19 | foreach (var x in GetValidValues(parameter))
|
---|
20 | if(x.ToString() == cdata.Value)
|
---|
21 | parameter.ActualValue = x;
|
---|
22 |
|
---|
23 | if (parameter.ActualValue != null && parameter.ActualValue is IParameterizedItem && cdata.Children != null) {
|
---|
24 | foreach(var child in cdata.Children) {
|
---|
25 | if(child.Name == cdata.Value || child.Path.EndsWith(cdata.Value) || child.Name == parameter.ActualValue.ItemName)
|
---|
26 | root.Inject(parameter.ActualValue, child, root);
|
---|
27 | }
|
---|
28 | }
|
---|
29 | }
|
---|
30 |
|
---|
31 | public override IJsonItem Extract(IItem value, IJsonItemConverter root) {
|
---|
32 | IParameter parameter = value as IParameter;
|
---|
33 |
|
---|
34 | IJsonItem item = new StringJsonItem() {
|
---|
35 | Name = parameter.Name,
|
---|
36 | Description = value.ItemDescription,
|
---|
37 | Value = parameter.ActualValue?.ToString(),
|
---|
38 | ConcreteRestrictedItems = GetValidValues(parameter).Select(x => x.ToString())
|
---|
39 | };
|
---|
40 | item.AddChildren(GetParameterizedChilds(parameter, root));
|
---|
41 |
|
---|
42 | return item;
|
---|
43 | }
|
---|
44 |
|
---|
45 | #region Helper
|
---|
46 | private IItem[] GetValidValues(IParameter value) {
|
---|
47 | List<IItem> list = new List<IItem>();
|
---|
48 | var values = ((dynamic)value).ValidValues;
|
---|
49 | foreach (var x in values) list.Add((IItem)x);
|
---|
50 | return list.ToArray();
|
---|
51 | }
|
---|
52 |
|
---|
53 | private IList<IJsonItem> GetParameterizedChilds(IParameter value, IJsonItemConverter root) {
|
---|
54 | List<IJsonItem> list = new List<IJsonItem>();
|
---|
55 | var values = ((dynamic)value).ValidValues;
|
---|
56 | foreach(var x in values) {
|
---|
57 | if (x is IParameterizedItem) { // only makes sense for IParameterizedItems to go deeper
|
---|
58 | IJsonItem tmp = root.Extract(x, root);
|
---|
59 | if(!(tmp is UnsupportedJsonItem))
|
---|
60 | list.Add(tmp);
|
---|
61 | }
|
---|
62 | }
|
---|
63 | return list.Count == 0 ? null : list;
|
---|
64 | }
|
---|
65 | #endregion
|
---|
66 | }
|
---|
67 | }
|
---|