using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.IO.Compression;

namespace pdinklag
{
    public class ScriptCollection : IReadOnlyDictionary<string, string>
    {
        private readonly Dictionary<string, string> _scripts;

        public ScriptCollection(int initialCapacity)
        {
            _scripts = new(initialCapacity);
        }

        public ScriptCollection(byte[] data)
        {
            using (var stream = new MemoryStream(data))
            {
                using (var r = new BinaryReader(new GZipStream(stream, CompressionMode.Decompress)))
                {
                    var count = r.ReadInt32();
                    _scripts = new(count);

                    for (var i = 0; i < count; i++)
                    {
                        var key = r.ReadString();
                        var value = r.ReadString();
                        Add(key, value);
                    }
                }
            }
        }

        public byte[] Encode()
        {
            byte[] data;
            using (var stream = new MemoryStream())
            {
                using (var w = new BinaryWriter(new GZipStream(stream, CompressionLevel.Fastest, true)))
                {
                    w.Write(Count);
                    foreach (var e in this)
                    {
                        w.Write(e.Key);
                        w.Write(e.Value);
                    }
                }
                data = stream.GetBuffer();
            }
            return data;
        }

        public void Add(string filename, string script) => _scripts.Add(filename, script);

        public string this[string key] => _scripts[key];
        public IEnumerable<string> Keys => _scripts.Keys;
        public IEnumerable<string> Values => _scripts.Values;
        public int Count => _scripts.Count;
        public bool ContainsKey(string key) => _scripts.ContainsKey(key);
        public IEnumerator<KeyValuePair<string, string>> GetEnumerator() => _scripts.GetEnumerator();
        public bool TryGetValue(string key, out string value) => _scripts.TryGetValue(key, out value);
        IEnumerator IEnumerable.GetEnumerator() => _scripts.GetEnumerator();
    }
}
