using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; using FarmmapsApi; using FarmmapsApi.Models; using FarmmapsApi.Services; using FarmmapsNbs.Models; using Microsoft.Extensions.Logging; using Newtonsoft.Json; using static FarmmapsApiSamples.Constants; namespace FarmmapsNbs { public class NbsApplication : IApplication { private const string DownloadFolder = "Downloads"; private readonly ILogger _logger; private readonly FarmmapsApiService _farmmapsApiService; private readonly NitrogenService _nitrogenService; private readonly GeneralService _generalService; public NbsApplication(ILogger logger, FarmmapsApiService farmmapsApiService, GeneralService generalService, NitrogenService nitrogenService) { _logger = logger; _farmmapsApiService = farmmapsApiService; _generalService = generalService; _nitrogenService = nitrogenService; } public async Task RunAsync() { var nitrogenInputJson = File.ReadAllText("NitrogenInput.json"); List nitrogenInputs = JsonConvert.DeserializeObject>(nitrogenInputJson); if (!Directory.Exists(DownloadFolder)) Directory.CreateDirectory(DownloadFolder); // !! this call is needed the first time an api is called with a fresh clientid and secret !! await _farmmapsApiService.GetCurrentUserCodeAsync(); var roots = await _farmmapsApiService.GetCurrentUserRootsAsync(); foreach (var input in nitrogenInputs) { try { await Process(roots, input); } catch (Exception ex) { _logger.LogError(ex.Message); } } } private async Task Process(List roots, NitrogenInput input) { var plantingDate = input.PlantingDate; var measurementDate = input.MeasurementDate; var uploadedRoot = roots.SingleOrDefault(r => r.Name == "Uploaded"); if (uploadedRoot == null) { _logger.LogError("Could not find a needed root item"); return; } var myDriveRoot = roots.SingleOrDefault(r => r.Name == "My drive"); if (myDriveRoot == null) { _logger.LogError("Could not find a needed root item"); return; } var cropfieldItem = await _generalService.CreateCropfieldItemAsync(myDriveRoot.Code, $"VRA NBS cropfield {input.OutputFileName}", plantingDate.Year, input.GeometryJson.ToString(Formatting.None)); var isGeoJson = input.File.Contains("json"); var dataPath = Path.Combine("Data", input.File); var shapeItem = isGeoJson ? await _generalService.UploadDataAsync(uploadedRoot, SHAPE_PROCESSED_ITEMTYPE, dataPath, Path.GetFileNameWithoutExtension(input.File)): await _generalService.UploadZipWithShapeAsync(uploadedRoot, dataPath, Path.GetFileNameWithoutExtension(input.File)); if (shapeItem == null) { _logger.LogError("Could not find item for uploaded data"); return; } _logger.LogInformation($"Converting shape to geotiff"); var geotiffItem = await _generalService.ShapeToGeotiff(shapeItem); if (geotiffItem == null) { _logger.LogError("Something went wrong with shape to geotiff transformation"); return; } _logger.LogInformation($"Calculating targetN with targetYield: {input.TargetYield}"); var targetNItem = await _nitrogenService.CreateTargetNItem(cropfieldItem); var targetNData = await _nitrogenService.CalculateTargetN(cropfieldItem, targetNItem, plantingDate, measurementDate, input.PotatoPurposeType, input.TargetYield); if (targetNData == null) { _logger.LogError("Something went wrong with TargetN calculation"); return; } _logger.LogInformation($"TargetN: {targetNData.TargetN}"); var targetNDataPath = Path.Combine(DownloadFolder, $"{input.OutputFileName}.targetn.json"); await File.WriteAllTextAsync(targetNDataPath, JsonConvert.SerializeObject(targetNData, Formatting.Indented)); _logger.LogInformation("Calculating uptake map"); var uptakeMapItem = await _nitrogenService.CalculateUptakeMap(cropfieldItem, geotiffItem, plantingDate, measurementDate, input.InputVariable); if (uptakeMapItem == null) { _logger.LogError("Something went wrong with creating the uptakeMap"); return; } _logger.LogInformation("Downloading uptake map"); await _farmmapsApiService.DownloadItemAsync(uptakeMapItem.Code, Path.Combine(DownloadFolder, $"{input.OutputFileName}.uptake.zip")); _logger.LogInformation("Calculating application map"); var applicationMapItem = await _nitrogenService.CalculateApplicationMap(cropfieldItem, geotiffItem, plantingDate, measurementDate, input.InputVariable, targetNData.TargetN); if (applicationMapItem == null) { _logger.LogError("Something went wrong with creating the applicationMap"); return; } _logger.LogInformation("Downloading application map"); await _farmmapsApiService.DownloadItemAsync(applicationMapItem.Code, Path.Combine(DownloadFolder, $"{input.OutputFileName}.application.zip")); } } }