using DeepDrftAPI.Models;
using DeepDrftContent;
using DeepDrftContent.Constants;
using DeepDrftContent.FileDatabase.Models;
using DeepDrftContent.FileDatabase.Services;
using DeepDrftContent.Processors;
using Microsoft.Extensions.Logging;
using NetBlocks.Utilities.Environment;

namespace DeepDrftAPI
{
    public static class Startup
    {
        public static Task ConfigureDomainServices(WebApplicationBuilder builder)
        {
            // Audio services
            builder.Services.AddSingleton<AudioProcessor>();
            builder.Services.AddSingleton<Mp3AudioProcessor>();
            builder.Services.AddSingleton<FlacAudioProcessor>();
            builder.Services.AddSingleton<AudioProcessorRouter>();
            builder.Services.AddSingleton<TrackContentService>();

            // Image services
            builder.Services.AddSingleton<ImageProcessor>();

            // Waveform loudness profiling (upload-time, off the playback path)
            builder.Services.Configure<WaveformProfileOptions>(
                builder.Configuration.GetSection(nameof(WaveformProfileOptions)));
            builder.Services.AddSingleton<ILoudnessAlgorithm, RmsLoudnessAlgorithm>();
            builder.Services.AddSingleton<WaveformProfileService>();

            // File Database
            var fileDatabasePath = CredentialTools.ResolvePathOrThrow("filedatabase", "environment/filedatabase.json");
            builder.Configuration.AddJsonFile(fileDatabasePath, optional: false, reloadOnChange: false);
            var fileDatabaseSettings = builder.Configuration.GetSection(nameof(FileDatabaseSettings)).Get<FileDatabaseSettings>();
            if (fileDatabaseSettings is null) { throw new Exception("File database settings are not configured"); }

            var vaultPath = fileDatabaseSettings.VaultPath;
            builder.Services.AddSingleton(sp =>
            {
                var logger = sp.GetRequiredService<ILogger<FileDatabase>>();
                var db = FileDatabase.FromAsync(vaultPath, logger).GetAwaiter().GetResult();
                if (db is null) throw new Exception("Unable to initialize file database");
                InitializeTrackVault(db).GetAwaiter().GetResult();
                InitializeImageVault(db).GetAwaiter().GetResult();
                InitializeMixWaveformsVault(db).GetAwaiter().GetResult();
                return db;
            });

            return Task.CompletedTask;
        }

        private static async Task InitializeTrackVault(FileDatabase fileDatabase)
        {
            if (!fileDatabase.HasVault(VaultConstants.Tracks))
            {
                await fileDatabase.CreateVaultAsync(VaultConstants.Tracks, MediaVaultType.Audio);
            }
        }

        private static async Task InitializeImageVault(FileDatabase fileDatabase)
        {
            if (!fileDatabase.HasVault(VaultConstants.Images))
            {
                await fileDatabase.CreateVaultAsync(VaultConstants.Images, MediaVaultType.Image);
            }
        }

        // Ensure the mix-waveforms vault exists. Holds high-resolution waveform datums for DJ Mix releases.
        private static async Task InitializeMixWaveformsVault(FileDatabase fileDatabase)
        {
            if (!fileDatabase.HasVault(VaultConstants.MixWaveforms))
            {
                await fileDatabase.CreateVaultAsync(VaultConstants.MixWaveforms, MediaVaultType.Media);
            }
        }
    }
}