using System;
using System.Collections.Generic;

namespace Cute;

public class ManifestDatahashKVS : ILocalKVS, IDisposable
{
	protected LocalSqliteKVS _kvs;

	public string savePath => _kvs.savePath;

	public ManifestDatahashKVS(string path)
	{
		_kvs = LocalSqliteKVS.Open(path, enableCache: true);
	}

	~ManifestDatahashKVS()
	{
		Dispose();
	}

	public virtual void Dispose()
	{
		if (_kvs != null)
		{
			_kvs.Dispose();
			_kvs = null;
		}
	}

	public string Get(string name)
	{
		string text = _kvs.Get(name);
		return (text == null) ? "" : text;
	}

	public void Set(string name, string hash)
	{
		_kvs.Set(name, hash);
	}

	public void Set(Dictionary<string, string> _dictionary)
	{
		if (_dictionary.Count <= 0)
		{
			return;
		}
		foreach (KeyValuePair<string, string> item in _dictionary)
		{
			Set(item.Key, item.Value);
		}
	}

	public void Delete(string name)
	{
		_kvs.Delete(name);
	}

	public void DeleteAll()
	{
		_kvs.DeleteAll();
		Optimize();
	}

	public void DisableCache()
	{
		_kvs.DisableCache();
	}

	public void DeleteByList(List<string> _deleteList)
	{
		if (_deleteList.Count > 0)
		{
			Transaction(delegate
			{
				_deleteList.ForEach(Delete);
			});
			Optimize();
		}
	}

	public void DeleteByPrefix(string prefix)
	{
		List<string> deleteList = _kvs.FindLike(_kvs.EscapeLikePattern(prefix) + "%");
		if (deleteList.Count <= 0)
		{
			return;
		}
		Transaction(delegate
		{
			foreach (string item in deleteList)
			{
				Delete(item);
			}
		});
		Optimize();
	}

	public List<string> GetAll()
	{
		return _kvs.GetAll();
	}

	public List<string> FindLike(string patternEscaped)
	{
		return _kvs.FindLike(patternEscaped);
	}

	public string EscapeLikePattern(string patternNoEscape)
	{
		return _kvs.EscapeLikePattern(patternNoEscape);
	}

	public void Optimize()
	{
		_kvs.Optimize();
	}

	public void Transaction(Action block)
	{
		_kvs.Transaction(block);
	}
}
