using Lookup.Memory;

namespace Lookup.IO;

/// <summary>
/// <see cref="Interface.ILookup{TKey,TValue}"/>
/// implementation, which stores data in <see cref="ICollection{T}"/>s.
/// Supports writing the stored data to a file.
/// </summary>
/// <typeparam name="TKey">Type of the key referencing the <typeparamref name="TValue"/>s</typeparam>
/// <typeparam name="TValue">Type of the stored values, referenced by <typeparamref name="TKey"/></typeparam>
public class FileLookup<TKey, TValue> : MemoryLookup<TKey, TValue>
{
  public string Path { get; set; }

  public FileLookup(string path)
  {
    Path = path;
  }

  public void Save()
  {
    using var writer = new StreamWriter(System.IO.File.Create(Path));
    foreach (var kv in this)
    {
      writer.WriteLine($"{kv.Key};{string.Join(',', kv.Value)}");
    }
  }

  public new void Clear()
  {
    base.Clear();

    if (System.IO.File.Exists(Path))
    {
      System.IO.File.Delete(Path);
    }
  }
}