From 9dc247a861be845ff79ce38430ace2591d187975 Mon Sep 17 00:00:00 2001
From: Jakob Stendahl <jakob.stendahl@outlook.com>
Date: Wed, 27 Apr 2022 00:32:41 +0200
Subject: Move all data fetching to a store, add spinner for loading

---
 src/components/WeatherCurrent.svelte | 153 ++++++++++-------------------------
 1 file changed, 41 insertions(+), 112 deletions(-)

(limited to 'src/components/WeatherCurrent.svelte')

diff --git a/src/components/WeatherCurrent.svelte b/src/components/WeatherCurrent.svelte
index 7ca6ac4..45bfe11 100644
--- a/src/components/WeatherCurrent.svelte
+++ b/src/components/WeatherCurrent.svelte
@@ -1,100 +1,11 @@
 <script lang="ts">
-    import { onMount } from 'svelte';
+    import SpinnerRoller from './Spinner/SpinnerRoller.svelte';
 
+    import { onMount } from 'svelte';
+    import { navigator_location, earth_weather, space_weather } from '../stores';
     const monthNames = ["January", "February", "March", "April", "May", "June",
       "July", "August", "September", "October", "November", "December"
     ];
-
-    let longitude;
-	let latitude;
-	let locationSupported;
-	let dataLoading = true;
-
-    let location = "-";
-    let date = "-";
-    let kp_now = "-";
-    let kp_min = "-";
-    let kp_max = "-";
-    let bz = "-";
-    let clouds = "-";
-    let temp = "-";
-
-    async function getMETNorData(longitude, latitude) {
-        let yr_data = await fetch(`https://api.met.no/weatherapi/locationforecast/2.0/compact?lat=${latitude}&lon=${longitude}`).then(res => res.json());
-        clouds = yr_data["properties"]["timeseries"][0]["data"]["instant"]["details"]["cloud_area_fraction"];
-        temp =  yr_data["properties"]["timeseries"][0]["data"]["instant"]["details"]["air_temperature"];
-    }
-
-    async function getLocation(longitude, latitude) {
-        console.log(`https://geocode.xyz/${longitude},${latitude}?geoit=json`);
-        let locDat = await fetch(`https://geocode.xyz/${latitude},${longitude}?geoit=json`).then(r => r.json());
-        console.log(locDat);
-        location = locDat["city"];
-    }
-
-    async function getUSNOAAData() {
-        bz = (await fetch("https://services.swpc.noaa.gov/products/summary/solar-wind-mag-field.json").then(res => res.json()))["Bz"];
-        let kp_data = (await fetch('https://services.swpc.noaa.gov/products/noaa-planetary-k-index-forecast.json').then(res => res.json()));
-        kp_data.shift();
-
-        let cDate = new Date();
-        let closestDate = new Date(0,0,0);
-        let minkp = 1000; // Just a larger number than any plausable value
-        let maxkp = 0;
-
-        kp_data.forEach((pred, i) => {
-            if (pred[1] > maxkp) {
-                maxkp = pred[1];
-            }
-            if (pred[1] < minkp) {
-                minkp = pred[1];
-            }
-            let predDate = new Date(pred[0]);
-            if (Math.abs(predDate.getTime() - cDate.getTime()) < Math.abs(closestDate.getTime() - cDate.getTime())) {
-                closestDate = predDate;
-                kp_now = pred[1];
-            }
-        });
-        kp_min = minkp.toString();
-        kp_max = maxkp.toString();
-
-        date = closestDate.getDay() + ". " + monthNames[closestDate.getMonth()] + " " + closestDate.getHours() + ":" + closestDate.getMinutes();
-    }
-
-	function fetchData() {
-        getUSNOAAData();
-
-		if (navigator.geolocation) {
-			dataLoading = true
-			locationSupported = true
-			navigator.geolocation.getCurrentPosition(setLocation, locationError)
-		} else {
-    		locationSupported = false
-			noLocation()
-		}
-	}
-
-	function setLocation(position) {
-		longitude = position.coords.longitude
-		latitude = position.coords.latitude
-		getMETNorData(longitude, latitude)
-        getLocation(longitude, latitude);
-	}
-
-	function locationError(err) {
-		noLocation()
-	}
-
-	function noLocation() {
-		longitude = 28.283333
-		latitude = -15.416667
-		toggleLoading()
-	}
-	function toggleLoading() {
-		dataLoading = !dataLoading
-	}
-
-    onMount(fetchData);
 </script>
 
 <style>
@@ -138,6 +49,7 @@
         display: flex;
         justify-content: center;
         align-content: center;
+        align-items: flex-end;
     }
 
     .weatherCurrent-data-location .symbol {
@@ -181,35 +93,52 @@
 <div class="weatherCurrent-wrapper">
     <div class="weatherCurrent-data">
         <div class="weatherCurrent-data-location">
-            <i class="symbol fas fa-map-marker-alt"></i>
-            <h1>{location}</h1>
+            {#if !$navigator_location.updating && $navigator_location.available}
+                <i class="symbol fas fa-map-marker-alt"></i>
+                <h1>{$navigator_location.city}</h1>
+            {/if}
         </div>
 
         <div class="weatherCurrent-data-date">
-            <p>{date}</p>
+        {#if $earth_weather.updating || $space_weather.updating}
+        {:else}
+            {#if Math.abs($earth_weather.updated - $space_weather.updated) > 60*10*1000}
+                <p>There is more than 10 minutes difference between data updates</p>
+            {:else}
+                <p>{$earth_weather.updated.toLocaleString("no-NO", {dateStyle: "medium", timeStyle: "short"})}</p>
+            {/if}
+        {/if}
         </div>
 
         <div class="weatherCurrent-data-kp">
-            <h2>KP {kp_now}</h2>
-            <p>
-                <span className="pr-2">&uarr; KP {kp_max}</span>
-                <span className="pl-2">&darr; KP {kp_min}</span>
-            </p>
+            {#if $space_weather.updating || $earth_weather.updating}
+                <SpinnerRoller />
+            {:else}
+                <h2>KP {$space_weather.now.kp}</h2>
+                <p>
+                    <span className="pr-2">&uarr; KP {$space_weather.now.kp_max}</span>
+                    <span className="pl-2">&darr; KP {$space_weather.now.kp_min}</span>
+                </p>
+            {/if}
         </div>
 
         <div class="current-details">
-            <div>
-                <p>BZ</p>
-                <p>{bz}</p>
-            </div>
-            <div>
-                <p>Temp</p>
-                <p>{temp}°C</p>
-            </div>
-            <div>
-                <p>Clouds</p>
-                <p>{clouds}%</p>
-            </div>
+            {#if !$space_weather.updating && !$earth_weather.updating}
+                <div>
+                    <p>BZ</p>
+                    <p>{$space_weather.now.bz}</p>
+                </div>
+                {#if $earth_weather.available}
+                <div>
+                    <p>Temp</p>
+                    <p>{$earth_weather.now.temp}°C</p>
+                </div>
+                <div>
+                    <p>Clouds</p>
+                    <p>{$earth_weather.now.clouds}%</p>
+                </div>
+                {/if}
+            {/if}
         </div>
 
     </div>
-- 
cgit v1.2.3

