﻿using System;
using System.IO;

namespace Oni.Sound
{
	internal class AifImporter : Importer
	{
		private const int fcc_ima4 = 0x696d6134;
		private static readonly byte[] sampleRate = new byte[10] { 0x40, 0x0d, 0xac, 0x44, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };

		public AifImporter()
			: base(InstanceFileHeader.OniMacTemplateChecksum)
		{
		}

		public override void Import(string filePath, string outputDirPath)
		{
			var aif = AifFile.FromFile(filePath);

			if (aif.Format != fcc_ima4)
			{
				Console.Error.WriteLine("Unsupported AIF compression (0x{0:X})", aif.Format);
				return;
			}

			if (!Utils.ArrayEquals(aif.SampleRate, sampleRate))
			{
				Console.Error.WriteLine("Unsupported sample rate");
				return;
			}

			if (aif.ChannelCount != 1 && aif.ChannelCount != 2)
			{
				Console.Error.WriteLine("Unsupported number of channels ({0})", aif.ChannelCount);
				return;
			}

			BeginImport();
			WriteSNDD(Path.GetFileNameWithoutExtension(filePath), aif);
			Write(outputDirPath);
		}

		private void WriteSNDD(string name, AifFile aif)
		{
            int duration = (int)(aif.SampleFrames * 64.0f / 22050.0f * 60.0f);

            var sndd = CreateInstance(TemplateTag.SNDD, name);

            using (var writer = sndd.OpenWrite())
            {
                writer.Write((aif.ChannelCount == 1) ? 1 : 3);
                writer.Write(duration);
                writer.Write(aif.SoundData.Length);
                writer.Write(WriteRawPart(aif.SoundData));
                writer.Skip(8);
            }
		}
	}
}
