using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using FarmmapsApi.Models; using FarmmapsApi.Services; using FarmmapsHaulmkilling.Models; using Microsoft.Extensions.Logging; using Newtonsoft.Json; using static FarmmapsApi.Extensions; using static FarmmapsApiSamples.Constants; namespace FarmmapsHaulmkilling { public class HaulmkillingService { private readonly ILogger _logger; private readonly FarmmapsApiService _farmmapsApiService; private readonly GeneralService _generalService; public HaulmkillingService(ILogger logger, FarmmapsApiService farmmapsApiService, GeneralService generalService) { _logger = logger; _farmmapsApiService = farmmapsApiService; _generalService = generalService; } /// /// Gets the list of available haulmkilling agents /// /// List of haulmkilling agents public async Task> GetHaulmkillingAgents() { var itemType = "vnd.farmmaps.itemtype.codelist.fm005"; var haulmkillingAgentItems = await _farmmapsApiService.GetItemsAsync(string.Empty, itemType); return haulmkillingAgentItems.Select(item => item.Data.ToObject()) .ToList(); } /// /// Creates an haulmkilling application map /// /// The context cropfield item to use /// The geotiff item to use /// WDVI or NDVI /// code of one of the available agents /// One of the available options /// Haulmkilling application map item public async Task CalculateApplicationMapAsync(Item cropfieldItem, Item inputItem, string inputType, string selectedOption, HaulmkillingAgent agent) { var taskRequest = new TaskRequest() { TaskType = "vnd.farmmaps.task.vrahaulmkilling" }; taskRequest.attributes["inputCode"] = inputItem.Code; taskRequest.attributes["inputType"] = inputType; taskRequest.attributes["agentCode"] = agent.Code; taskRequest.attributes["selectedOption"] = selectedOption; taskRequest.attributes["minPercentile"] = "0.0"; var taskCode = await _farmmapsApiService.QueueTaskAsync(cropfieldItem.Code, taskRequest); await PollTask(TimeSpan.FromSeconds(3), async (tokenSource) => { _logger.LogInformation("Checking vrahaulmkilling 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 = $"VRAHaulmkilling {agent.Label}"; var applianceMapItem = await _generalService.FindChildItemAsync(cropfieldItem.Code, GEOTIFF_PROCESSED_ITEMTYPE, itemName, i => i.Updated >= itemTask.Finished && i.Name.ToLower().Contains(itemName.ToLower())); if (applianceMapItem == null) { _logger.LogError("Could not find the VRAHaulmkilling geotiff child item under cropfield"); return null; } return applianceMapItem; } } }