using Managing.Application.Abstractions.Repositories;
using Managing.Application.Abstractions.Services;
using Managing.Common;
using Managing.Domain.Workers;

namespace Managing.Application.Workers;

public class WorkerService : IWorkerService
{
    private readonly IWorkerRepository _workerRepository;

    public WorkerService(IWorkerRepository workerRepository)
    {
        _workerRepository = workerRepository;
    }

    public async Task<Worker> GetWorker(Enums.WorkerType workerType)
    {
        return await _workerRepository.GetWorkerAsync(workerType);
    }

    public async Task InsertWorker(Enums.WorkerType workerType, TimeSpan delay)
    {
        var worker = new Worker()
        {
            WorkerType = workerType,
            StartTime = DateTime.UtcNow,
            LastRunTime = null,
            ExecutionCount = 0,
            Delay = delay
        };
        await _workerRepository.InsertWorker(worker);
    }

    public async Task UpdateWorker(Enums.WorkerType workerType, int executionCount)
    {
        await _workerRepository.UpdateWorker(workerType, executionCount);
    }

    public async Task DisableWorker(Enums.WorkerType workerType)
    {
        await _workerRepository.DisableWorker(workerType);
    }

    public async Task EnableWorker(Enums.WorkerType workerType)
    {
        await _workerRepository.EnableWorker(workerType);
    }

    public async Task<IEnumerable<Worker>> GetWorkers()
    {
        return await _workerRepository.GetWorkers();
    }

    public async Task<bool> ToggleWorker(Enums.WorkerType workerType)
    {
        var worker = await GetWorker(workerType);
        if (worker.IsActive)
        {
            _ = _workerRepository.DisableWorker(workerType);
            return false;
        }
        else
        {
            _ = _workerRepository.EnableWorker(workerType);
            return true;
        }
    }
}