From 69522820afc1b24b029c4a0fec274de4c7d4f30d Mon Sep 17 00:00:00 2001
From: Tor-Einar Skog <tor-einar.skog@nibio.no>
Date: Wed, 28 Feb 2024 10:41:44 +0100
Subject: [PATCH] Add trimming of weather data object

---
 ipmd/static/ipmd/js/ipmdlib.js | 56 ++++++++++++++++++++++++++++++++++
 1 file changed, 56 insertions(+)

diff --git a/ipmd/static/ipmd/js/ipmdlib.js b/ipmd/static/ipmd/js/ipmdlib.js
index ecdf682f..29323adb 100644
--- a/ipmd/static/ipmd/js/ipmdlib.js
+++ b/ipmd/static/ipmd/js/ipmdlib.js
@@ -531,9 +531,65 @@ function mergeWeatherData(primaryData, secondaryData)
     }
 
     mergedData.locationWeatherData[0].data = dataSet;
+    trimWeatherData(mergedData);
     return mergedData;
 }
 
+/**
+ * Removes NULL rows at the beginning and end of a dataset
+ * Assumes only one locationWeatherData
+ * @param {Object} weatherData 
+ */
+function trimWeatherData(weatherData)
+{
+    // Find index of first and last non-NULL rows
+    let firstIndex = 0;
+    outer_loop_first:
+    for(let i=0; i<weatherData.locationWeatherData[0].data.length; i++)
+    {
+        let row = weatherData.locationWeatherData[0].data[i];
+        if(row != undefined && row != null )
+        {
+            for(let j=0;j<row.length;j++)
+            {
+                if(row[j] != undefined && row[j] != null)
+                {
+                    firstIndex = i;
+                    break outer_loop_first;
+                }
+            }
+        }
+    }
+
+    let lastIndex = weatherData.locationWeatherData[0].data.length -1;
+    outer_loop_last:
+    for(let i=lastIndex; i>=0; i--)
+    {
+        let row = weatherData.locationWeatherData[0].data[i];
+        if(row != undefined && row != null )
+        {
+            for(let j=0;j<row.length;j++)
+            {
+                if(row[j] != undefined && row[j] != null)
+                {
+                    lastIndex = i;
+                    break outer_loop_last;
+                }
+            }
+        }
+    }
+
+    
+
+    // Adjust timeStart and timeEnd based on indexes
+    let adjustedTimeStart = moment(weatherData.timeStart).add(firstIndex, (weatherData.interval == 86400 ? 'days' : 'hours'));
+    let adjustedTimeEnd   = moment(weatherData.timeEnd).subtract(weatherData.locationWeatherData[0].data.length -1 - lastIndex, (weatherData.interval == 86400 ? 'days' : 'hours'));
+    
+    weatherData.timeStart = adjustedTimeStart;
+    weatherData.timeEnd = adjustedTimeEnd;
+    weatherData.locationWeatherData[0].data = weatherData.locationWeatherData[0].data.slice(firstIndex, lastIndex + 1);
+}
+
 /**
  * Util method if you don't know the type of object you're trying to get a Unix timestamp from
  * @param {Object} aDate 
-- 
GitLab