using System;
using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;
using System.Linq;
using async_enumerable_dotnet;
using System.Threading;
using Dacryptero.Data;

namespace Dacryptero.DB
{
    public class DBMultiController : DBSession
    {
        public async Task LoadController(string directoryPath)
        {
            if (!Directory.Exists(directoryPath))
            {
                Serilog.Log.Information("DB Directoy not found: {path}", directoryPath);
                return;
            }
            controller.Clear();
            await Task.WhenAll(
                Directory.EnumerateDirectories(directoryPath)
                    .Select(async x => 
                        {
                            var config = await DBConfig
                                .TryParseAsync(Path.Combine(x, "config.json"))
                                .ConfigureAwait(false);
                            if (config is null)
                            {
                                Serilog.Log.Warning("Cannot load configuration for {path}", x);
                            }
                            else
                            {
                                controller.Add(new DBSingleController(config));
                            }
                        }
                    )
            );
            UpdateControllerList();
        }

    }
}