using Cryville.Common.Pdt;
using System;
using System.Collections.Generic;
using System.Reflection;

namespace Cryville.Crtr {
	internal class RulesetInterpreter : PdtInterpreter<PdtRuleset> {
		public RulesetInterpreter(string src, Binder binder) : base(src, binder) { }

		readonly List<RulesetSelector> s = new List<RulesetSelector>();
		readonly List<string> a = new List<string>();
		protected override object InterpretKey(Type type) {
			if (type == typeof(Constraint)) {
				s.Clear(); a.Clear();
				string key = "";
				while (true) {
					int pp = Position;
					switch (cc) {
						case '@':
							GetChar();
							a.Add(GetIdentifier());
							break;
						case '$':
							GetChar();
							s.Add(new RulesetSelector.CreateItem());
							key = null;
							break;
						case '#':
							GetChar();
							s.Add(new RulesetSelector.Index());
							break;
						case '>':
							GetChar();
							s.Add(new RulesetSelector.Property(GetExp()));
							break;
						case ';':
						case ':':
							return new PropertyKey(a.Contains("var") ? PropertyType.Variable : PropertyType.Property, key);
						case '{':
							return new RulesetSelectors(s);
						case '}':
							return null;
						default:
							var p4 = GetIdentifier();
							s.Add(new RulesetSelector.EventType(p4));
							if (key != null) key += p4;
							break;
					}
					ws();
					if (Position == pp) throw new FormatException("Invalid selector or key format");
				}
			}
			else return base.InterpretKey(type);
		}
	}
}
