using Cryville.Audio.Source.Libav;
using System.Collections.Generic;
using System.IO;

namespace Cryville.Crtr.Event {
	public class ChartHandler : TransformHandler {
		protected override TransformHandler Parent { get { return null; } }

		readonly Chart chart;
		readonly List<LibavFileAudioSource> sounds = new List<LibavFileAudioSource>();

		public ChartHandler(Chart _chart) {
			chart = _chart;
		}

		public override string TypeName { get { return "chart"; } }

		public override void PreInit() {
			base.PreInit();
		}

		public override void Update(ContainerState s, StampedEvent ev) {
			base.Update(s, ev);
			if (s.CloneType == 16) {
				if (ev == null) { }
				else if (ev.Unstamped == null) { }
				else if (ev.Unstamped is Chart.Sound) {
					Chart.Sound tev = (Chart.Sound)ev.Unstamped;
					var dir = new DirectoryInfo(Game.GameDataPath + "/songs/" + tev.id);
					var files = dir.GetFiles();
					var source = new LibavFileAudioSource(files[0].FullName);
					source.SelectStream();
					sounds.Add(source);
					Game.AudioSession.Sequence(
						s.Time - tev.offset + ChartPlayer.soundOffset,
						source
					);
				}
			}
		}

		public override void EndLogicalUpdate(ContainerState s) {
			base.EndLogicalUpdate(s);
			// TODO End of chart
		}

		public override void DisposeAll() {
			base.DisposeAll();
			foreach (var s in sounds) s.Dispose();
		}
	}
}
