using Cryville.Common;
using Cryville.Common.Collections.Specialized;
using Cryville.Crtr.Ruleset;
using System;
using System.Collections.Generic;

namespace Cryville.Crtr.Config {
	public class RulesetConfigStore {
		readonly IntKeyedDictionary<PropSrc> _srcs = new IntKeyedDictionary<PropSrc>();
		readonly Dictionary<string, int> _revMap = new Dictionary<string, int>();
		readonly Dictionary<string, object> _values;
		public RulesetConfigStore(Dictionary<Identifier, ConfigDefinition> defs, Dictionary<string, object> values) {
			_values = values;
			if (defs == null) return;
			foreach (var def in defs) {
				var key = def.Key.Key;
				var name = (string)def.Key.Name;
				if (!_values.ContainsKey(name)) {
					double value = 0;
					PdtEvaluator.Instance.Evaluate(new PropOp.Float(v => value = v), def.Value.@default);
					_values.Add(name, value);
				}
				_revMap.Add(name, key);
				_srcs.Add(key, new PropSrc.Float(() => {
					float result = 0;
					PdtEvaluator.Instance.ContextSelfValue = new PropSrc.Float(() => Convert.ToSingle(_values[name]));
					PdtEvaluator.Instance.Evaluate(new PropOp.Float(v => result = v), def.Value.value);
					PdtEvaluator.Instance.ContextSelfValue = null;
					return result;
				}));
			}
		}
		public object this[string key] {
			get { return _values[key]; }
			set {
				_values[key] = value;
				_srcs[_revMap[key]].Invalidate();
			}
		}
		public bool TryGetMappedSource(int key, out PropSrc result) {
			return _srcs.TryGetValue(key, out result);
		}
	}
}
