namespace HeuristicLab.Problems.ProgramSynthesis.Base.Erc { using System; using System.Collections.Generic; using System.Linq; using HeuristicLab.Common; using HeuristicLab.Core; using HeuristicLab.Persistence.Default.CompositeSerializers.Storable; using HeuristicLab.Problems.ProgramSynthesis.Base.Extensions; [StorableClass] public abstract class ErcOptionConvertible : CheckedItemCollection>, IErcItem { [Storable] protected bool isEnabled; public event EventHandler EnabledChanged; protected ErcOptionConvertible() : this(false, new WeightedErcItem[0]) { } protected ErcOptionConvertible(bool isEnabled, params WeightedErcItem[] values) : base(values) { this.isEnabled = isEnabled; SetEnabledChangedHandler(values); foreach (var value in values) SetItemCheckedState(value, value.IsEnabled); } [StorableConstructor] protected ErcOptionConvertible(bool deserializing) : base(deserializing) { } [StorableHook(HookType.AfterDeserialization)] // ReSharper disable once UnusedMember.Local private void AfterDeserialization() { SetEnabledChangedHandler(list); } protected ErcOptionConvertible(ErcOptionConvertible origin, Cloner cloner) : base(origin, cloner) { IsEnabled = origin.IsEnabled; } private void SetEnabledChangedHandler(IEnumerable> values) { foreach (var item in values) item.EnabledChanged += ErcValueItemEnabledChanged; } protected override void OnItemsAdded(IEnumerable> items) { base.OnItemsAdded(items); SetEnabledChangedHandler(items); } protected override void OnItemsRemoved(IEnumerable> items) { base.OnItemsRemoved(items); foreach (var item in items) item.EnabledChanged -= ErcValueItemEnabledChanged; } private void ErcValueItemEnabledChanged(object sender, bool state) { SetItemCheckedState((WeightedErcItem)sender, state); } protected override void OnCheckedItemsChanged(IEnumerable> items) { base.OnCheckedItemsChanged(items); foreach (var item in items) { item.IsEnabled = ItemChecked(item); } } public bool IsEnabled { get { return isEnabled; } set { if (value == isEnabled) return; isEnabled = value; if (EnabledChanged != null) EnabledChanged(this, value); } } public abstract TValue GetErcValue(IRandom random); protected TValue GetErcValue(IRandom random, Converter converter) { if (Count == 0 || !IsEnabled) return default(TValue); var ercValueItem = list .Where(item => item.IsEnabled) .RandomWeightedOrDefault(random, x => x.Weight); return ercValueItem == null ? default(TValue) : converter(ercValueItem.GetErcValue(random)); } } }