using UnityEngine;
using System.Collections;
using System.IO;
using System.Collections.Generic;
using System;

namespace uGIF
{
	public class CaptureToGIFCustom
	{
		private static CaptureToGIFCustom _instance;
		public static CaptureToGIFCustom Instance
		{
			get
			{
				if(_instance == null)
				{
					_instance = new CaptureToGIFCustom();
				}
				return _instance;
			}
		}


		public List<Image> Frames = new List<Image>();
		public bool stop = false;

		[System.NonSerialized]
		public byte[] bytes = null;

        public IEnumerator Encode (float fps, int quality)
		{
			bytes = null;
			stop = false;
			Error.Log("Recording...", Color.green);
			yield return new WaitForSeconds(0.1f);
			yield return _Encode(fps, quality);
            Error.Log("Saving gif...", Color.green);
			yield return new WaitForSeconds(0.1f);
			yield return WaitForBytes();
		}

		IEnumerator WaitForBytes() {
			while(bytes == null) yield return new WaitForEndOfFrame();
            string fileName = string.Format("KF3Viewer_{0}.gif", DateTime.Now.ToString("yyyy-MM-dd_HH-mm-ss-fff"));
            string savePath = Path.GetFullPath(Path.Combine(Settings.ScreenshotDirectory, fileName));
            Directory.CreateDirectory(Settings.ScreenshotDirectory);
            File.WriteAllBytes(savePath, bytes);
            bytes = null;
            Error.Log($"GIF saved: {savePath}", Color.green);
			Frames.Clear();
			stop = false;
        }

		public IEnumerator _Encode (float fps, int quality)
		{
			var ge = new GIFEncoder ();
			ge.useGlobalColorTable = true;
			ge.repeat = 0;
			ge.FPS = fps;
			ge.quality = quality;
			ge.transparent = new Color32 (0, 0, 0, 0);
			ge.dispose = 2;

			var stream = new MemoryStream ();
			ge.Start (stream);
            while (!stop || Frames.Count > 0)
            {
				if(Frames.Count>0 && Frames[0] != null)
				{
					Frames[0].Flip();
					ge.AddFrame(Frames[0]);
					Frames.RemoveAt(0);
				}
				yield return 0;
            }
			ge.Finish ();
			bytes = stream.GetBuffer ();
			stream.Close ();
			yield break;
		}
	}
}