using Cryville.Audio.Source;
using Cryville.Crtr.Event;
using System;
using System.Collections.Generic;
using System.IO;

namespace Cryville.Crtr {
	public class ChartHandler : ContainerHandler {
		public Chart chart;
		readonly List<LibavFileAudioSource> sounds = new List<LibavFileAudioSource>();

		public ChartHandler(Chart _chart, DirectoryInfo dir) : base() {
			if (dir == null) throw new ArgumentNullException("dir");
			chart = _chart;
		}

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

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

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

		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 source = new LibavFileAudioSource(
						Game.GameDataPath + "/songs/" + tev.id + "/.ogg"
					);
					source.SelectStream();
					sounds.Add(source);
					Game.AudioSession.Sequence(
						s.Time - tev.offset + ChartPlayer.soundOffset,
						source
					);
				}
			}
		}

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