using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;

namespace Dacryptero.Data.Schema
{
    public static class SchemaCollection
    {
        public static Dictionary<string, SchemaFile> Schemas { get; }
            = new Dictionary<string, SchemaFile>();
        
        public static async Task LoadSchemas(string directory)
        {
            if (!Directory.Exists(directory))
            {
                Serilog.Log.Warning("Schema directory {dir} doesn't exists", directory);
                return;
            }

            foreach (var path in Directory.GetFiles(directory, "*.json", new EnumerationOptions
            {
                MatchCasing = MatchCasing.CaseInsensitive,
                MatchType = MatchType.Simple,
                RecurseSubdirectories = true,
                ReturnSpecialDirectories = false,
            }))
            {
                Serilog.Log.Information("Load Schema at {path}", path);
                var schema = await SchemaFile.TryLoadSchemaAsync(path)
                    .ConfigureAwait(false);
                if (schema is null)
                    continue;
                
                if (Schemas.ContainsKey(schema.Name))
                {
                    Serilog.Log.Warning("Schema Name {name} already loaded", schema.Name);
                    continue;
                }

                Schemas.Add(schema.Name, schema);
            }
        }
    }
}