using MangaReader.Core.Data;
using MangaReader.Core.Http;
using MangaReader.Core.Metadata;
using MangaReader.Core.Pipeline;
using MangaReader.Core.Search;
using MangaReader.Core.Sources.MangaDex.Api;
using MangaReader.Core.Sources.MangaDex.Metadata;
using MangaReader.Core.Sources.MangaDex.Search;
using MangaReader.Core.Sources.NatoManga.Api;
using MangaReader.Core.Sources.NatoManga.Metadata;
using MangaReader.Core.Sources.NatoManga.Search;
using Microsoft.EntityFrameworkCore;

#pragma warning disable IDE0130 // Namespace does not match folder structure
namespace Microsoft.Extensions.DependencyInjection;
#pragma warning restore IDE0130 // Namespace does not match folder structure

public static class ServiceCollectionExtensions
{
    public static IServiceCollection AddMangaReader(this IServiceCollection services, Action<DbContextOptionsBuilder>? optionsAction = null)
    {
        // Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:139.0) Gecko/20100101 Firefox/139.0
        services.AddHttpClient<IHttpService, HttpService>(client =>
        {
            client.DefaultRequestHeaders.UserAgent.ParseAdd("Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:139.0) Gecko/20100101 Firefox/139.0");
        });

        // Http
        services.AddScoped<IHttpService, HttpService>();
        services.AddScoped<IHtmlLoader, HtmlLoader>();

        // NatoManga
        //services.AddScoped<INatoMangaClient, NatoMangaClient>();
        //services.AddScoped<IMangaSearchProvider, NatoMangaSearchProvider>();
        //services.AddScoped<IMangaMetadataProvider, NatoMangaWebCrawler>();

        // MangaDex
        services.AddScoped<IMangaDexClient, MangaDexClient>();
        services.AddScoped<IMangaSearchProvider, MangaDexSearchProvider>();
        //services.AddScoped<IMangaMetadataProvider, MangaDexMetadataProvider>();
        services.AddKeyedScoped<IMangaMetadataProvider, MangaDexMetadataProvider>("MangaDex");

        services.AddScoped<IMangaSearchCoordinator, MangaSearchCoordinator>();
        services.AddScoped<IMangaMetadataCoordinator, MangaMetadataCoordinator>();

        services.AddScoped<IMangaPipeline, MangaPipeline>();

        // Database
        services.AddDbContext<MangaContext>(options =>
        {
            if (optionsAction is not null)
            {
                optionsAction(options);
            }
            else
            {
                var dbPath = Path.Combine(
                    Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),
                    "MangaReader",
                    "manga.db");

                Directory.CreateDirectory(Path.GetDirectoryName(dbPath)!);
                options.UseSqlite($"Data Source={dbPath}");
            }
        });

        return services;
    }
}