using System;
using System.Collections.Generic;
using System.Collections.Immutable;

namespace ExtensiblePortfolioSite.SDK.Resources.VFS
{
    internal class VirtualFolder : IVirtualFolder
    {
        public IVirtualFolder Parent { get; }
        public string Foldername { get; }

        internal VirtualFolder(IVirtualFolder Parent, String Foldername)
        {
            this.Foldername = Foldername;
            this.Parent = Parent;
        }

        private readonly SortedDictionary<String, IVirtualEntry> Entries = new();

        public IVirtualFile CreateFile(string Filename, IResource File)
        {
            IVirtualFile entry = new VirtualFile(this, Filename, File);
            lock (Entries)
                Entries.Add(Filename, entry);
            return entry;
        }

        public IVirtualFolder CreateFolder(string Foldername)
        {
            IVirtualFolder entry = new VirtualFolder(this, Foldername);
            lock (Entries)
                Entries.Add(Foldername, entry);
            return entry;
        }

        public void Delete(string Entry)
        {
            lock(Entries)
                Entries.Remove(Entry);
        }
        public void Delete() => this.Parent.Delete(this.Foldername);

        public IEnumerable<IVirtualEntry> EnumerateEntries()
        {
            foreach (IVirtualEntry Entry in Entries.Values.ToImmutableArray())
                yield return Entry;
        }
        public IVirtualEntry? GetEntry(string Entry)
        {
            Entries.TryGetValue(Entry, out IVirtualEntry? entry);
            return entry;
        }
    }
}
