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);
}
///
/// Запуск задачи по Id
///
/// Id задачи
///
///
[HttpGet("start/{workId}")]
public async Task 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 RestartAsync(CancellationToken token)
{
await worker.StopAsync(token);
await worker.StartAsync(token);
return Ok();
}
}