using FNZCM.Shared.MediaModels;
using Newtonsoft.Json;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace FNZCM.ConHost
{
    internal static class MetaCache
    {
        private static readonly string TagFilePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "MediaTag.json.lz4");

        public static void Clear() => File.Delete(TagFilePath);

        public static void Save(ConcurrentDictionary<string, MediaTag> tags)
        {
            var json = JsonConvert.SerializeObject(tags);
            var u8 = Encoding.UTF8.GetBytes(json);
            var lz4 = K4os.Compression.LZ4.LZ4Pickler.Pickle(u8);
            File.WriteAllBytes(TagFilePath, lz4);
        }

        public static ConcurrentDictionary<string, MediaTag> Load()
        {
            if (File.Exists(TagFilePath) == false) return null;

            var lz4 = File.ReadAllBytes(TagFilePath);
            var u8 = K4os.Compression.LZ4.LZ4Pickler.Unpickle(lz4);
            var json = Encoding.UTF8.GetString(u8);
            var tags = JsonConvert.DeserializeObject<ConcurrentDictionary<string, MediaTag>>(json);
            return tags;
        }
    }
}
