FarmMapsApiClient_KB34_MAST/FarmMapsBlight/BlightService.cs

67 lines
2.5 KiB
C#

using FarmmapsApi.Models;
using FarmmapsApi.Services;
using Microsoft.Extensions.Logging;
using System;
using System.Threading.Tasks;
using static FarmmapsApi.Extensions;
using static FarmmapsApiSamples.Constants;
namespace FarmMapsBlight
{
public class BlightService
{
private readonly ILogger<BlightService> _logger;
private readonly FarmmapsApiService _farmmapsApiService;
private readonly GeneralService _generalService;
public BlightService(ILogger<BlightService> logger, FarmmapsApiService farmmapsApiService,
GeneralService generalService)
{
_logger = logger;
_farmmapsApiService = farmmapsApiService;
_generalService = generalService;
}
public async Task<Item> CreateAdvice(Item cropfieldItem, DateTime plantingDate, DateTime emergeDate)
{
var taskRequest = new TaskRequest()
{
TaskType = "vnd.farmmaps.task.blight"
};
taskRequest.attributes["plantingDate"] = plantingDate.ToUniversalTime().ToString("o");
taskRequest.attributes["emergeDate"] = emergeDate.ToUniversalTime().ToString("o");
var taskCode = await _farmmapsApiService.QueueTaskAsync(cropfieldItem.Code, taskRequest);
await PollTask(TimeSpan.FromSeconds(3), async (tokenSource) =>
{
_logger.LogInformation("Checking blight task status");
var itemTaskStatus = await _farmmapsApiService.GetTaskStatusAsync(cropfieldItem.Code, taskCode);
if (itemTaskStatus.IsFinished)
tokenSource.Cancel();
});
var itemTask = await _farmmapsApiService.GetTaskStatusAsync(cropfieldItem.Code, taskCode);
if (itemTask.State == ItemTaskState.Error)
{
_logger.LogError($"Something went wrong with task execution: {itemTask.Message}");
return null;
}
var itemName = $"Blight";
var blightAdviceItem = await _generalService.FindChildItemAsync(cropfieldItem.Code,
BLIGHT_ITEMTYPE, itemName);
// incorrect filter task is finished after updating
// i => i.Updated >= itemTask.Finished && i.Name.ToLower().Contains(itemName.ToLower())
if (blightAdviceItem == null)
{
_logger.LogError("Could not find the blight item under cropfield");
return null;
}
return blightAdviceItem;
}
}
}