using UnityEngine;
using UnityEditor.AssetImporters;
using System.IO;
using System.Security.Cryptography;

namespace KitsuneCafe.Scripting
{
    [ScriptedImporter(1, "wasm")]
    public class WasmImporter : ScriptedImporter
    {
        public override void OnImportAsset(AssetImportContext ctx)
        {
            byte[] data = File.ReadAllBytes(ctx.assetPath);

            WasmAsset wasmAsset = ScriptableObject.CreateInstance<WasmAsset>();
            wasmAsset.data = data;

            var hash = Hash(data);
            ctx.AddObjectToAsset(hash.ToString(), wasmAsset);
            ctx.SetMainObject(wasmAsset);
        }

        private byte[] Hash(byte[] buffer)
        {
            using var md5 = MD5.Create();
            return md5.ComputeHash(buffer);
        }
    }
}