using Cryville.Crtr.Extension;
using Newtonsoft.Json;
using System.IO;
using System.Text;

namespace Cryville.Crtr.Extensions.Umg {
	public class ChartResourceImporter : ResourceConverter {
		static readonly string[] SUPPORTED_FORMATS = { ".umgc" };
		public override string[] GetSupportedFormats() {
			return SUPPORTED_FORMATS;
		}

		public override void Convert(FileInfo file, ConversionSession ses) {
			var meta = Path.Combine(file.Directory.FullName, "meta.json");
			if (!File.Exists(meta)) throw new FileNotFoundException("Meta file for the chart not found");
			using (StreamReader reader = new StreamReader(meta, Encoding.UTF8)) {
				var data = JsonConvert.DeserializeObject<ChartMeta>(reader.ReadToEnd());
				ses.AddResource(new ChartResource(data.name, file));
			}
		}
	}
	public class ChartResource : FileResource {
		public ChartResource(string name, FileInfo master) : base(name, master) {
			using (var reader = new StreamReader(master.FullName)) {
				var meta = JsonConvert.DeserializeObject<ChartMeta>(reader.ReadToEnd());
				Attachments.Add(new FileInfo(Path.Combine(master.Directory.FullName, meta.data + ".json")));
				if (meta.cover != null) Attachments.Add(new FileInfo(Path.Combine(master.Directory.FullName, meta.cover)));
			}
		}
	}
}
