using Berufsschule_HAM.Models;
using Berufsschule_HAM.Helpers;

namespace Berufsschule_HAM.Services;

public class ImagePreloadService : IHostedService
{
    private readonly LdapService _ldap;
    private readonly ILogger<HomeController> _logger;
    public ImagePreloadService(LdapService ldap, ILogger<HomeController> logger)
    {
        _ldap = ldap ?? throw new ArgumentNullException(nameof(ldap));
        _logger = logger;
    }

    public Task StartAsync(CancellationToken cancellationToken)
    {
        AdminSettingsModel adminSettingsModel = _ldap.GetAdminSettingsModelAsync().Result;

        if (adminSettingsModel.UserImagePreloadType is not null && adminSettingsModel.UserImagePreloadType != UserImagePreloadType.None)
        {
            IEnumerable<UserModel> users = _ldap.ListUsersAsync().Result;
            _logger.LogInformation("Preloading user images with preload type {adminSettingsModel.UserImagePreloadType}", [adminSettingsModel.UserImagePreloadType]);
            return ImageHelper.PreloadUsers(users, adminSettingsModel.UserImagePreloadType);
        }
        return Task.CompletedTask;
    }

    public Task StopAsync(CancellationToken cancellationToken)
    {
        return Task.CompletedTask;
    }
}