using Cryville.Common;
using Cryville.Common.Buffers;
using System.Collections.Generic;

namespace Cryville.Crtr.Event {
	internal class RMVPool {
		private class Bucket : ObjectPool<RealtimeMotionValue> {
			readonly MotionRegistry _reg;
			public Bucket(string name, int capacity) : base(capacity) {
				_reg = ChartPlayer.motionRegistry[name];
			}
			protected override RealtimeMotionValue Construct() {
				return new RealtimeMotionValue().Init(_reg.InitValue);
			}
		}
		static Dictionary<Identifier, Bucket> _buckets;
		public static void Prepare() {
			_buckets = new Dictionary<Identifier, Bucket>(ChartPlayer.motionRegistry.Count);
			foreach (var reg in ChartPlayer.motionRegistry)
				_buckets.Add(reg.Key, new Bucket(reg.Key, 4096));
		}

		readonly Dictionary<RealtimeMotionValue, string> _rented = new Dictionary<RealtimeMotionValue, string>();
		public RealtimeMotionValue Rent(Identifier name) {
			var n = name;
			var obj = _buckets[n].Rent();
			_rented.Add(obj, n);
			return obj;
		}
		public void Return(RealtimeMotionValue obj) {
			_buckets[_rented[obj]].Return(obj);
			_rented.Remove(obj);
		}
		public void ReturnAll() {
			foreach (var obj in _rented)
				_buckets[obj.Value].Return(obj.Key);
			_rented.Clear();
		}
	}
}
