using AsbCloudApp.Data;
using AsbCloudInfrastructure.Background;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;

namespace AsbCloudWebApi.Controllers;

[Route("api/[controller]")]
[Authorize]
[ApiController]
public class PeriodicBackgroundWorkerController : ControllerBase
{
    private readonly PeriodicBackgroundWorker worker;
    private readonly IServiceProvider serviceProvider;

    public PeriodicBackgroundWorkerController(
        PeriodicBackgroundWorker worker,
        IServiceProvider serviceProvider)
    {
        this.worker = worker;
        this.serviceProvider = serviceProvider;
    }

    [HttpGet]
    public IActionResult GetAll()
    {
        var result = new
        {
            currentWork = (BackgroundWorkDto?)worker.CurrentWork,
            worker.MainLoopLastException,
            works = worker.Works.Select(work => (BackgroundWorkDto)work.Work),
        };
        return Ok(result);
    }

    /// <summary>
    /// Запуск задачи по Id
    /// </summary>
    /// <param name="workId">Id задачи</param>
    /// <param name="token"></param>
    /// <returns></returns>
    [HttpGet("start/{workId}")]
    public async Task<IActionResult> Start(string workId, CancellationToken token)
    {
        var targetWork = worker.Works.FirstOrDefault(w => w.Work.Id == workId);
        if(targetWork is not null)
        {
            using (var scope = serviceProvider.CreateScope()) {

                var result = await targetWork.Work.Start(scope.ServiceProvider, token);
                return Ok(result);
            }                
        }
        return BadRequest("Work not found by workId");
    }

    [HttpPost("restart"), Obsolete("temporary method")]
    public async Task<IActionResult> RestartAsync(CancellationToken token)
    {
        await worker.StopAsync(token);
        await worker.StartAsync(token);
        return Ok();
    }
}