From 120414ac59bb8ca2f1326f64a48cb4941e3a0267 Mon Sep 17 00:00:00 2001
From: Athanasius <github@miggy.org>
Date: Wed, 25 Aug 2021 14:08:36 +0100
Subject: [PATCH] CAPI: Convert StatsDialog.showstats() to using cached CAPI
 data

This will just bail if no data has yet been received for /profile, but
that's the same behaviour as if we don't yet have `monitor.cmdr`.
---
 companion.py |  8 ++++++++
 stats.py     | 37 ++++++++++++++++---------------------
 2 files changed, 24 insertions(+), 21 deletions(-)

diff --git a/companion.py b/companion.py
index a1d7b391..a6e80345 100644
--- a/companion.py
+++ b/companion.py
@@ -167,6 +167,14 @@ class CAPIDataRaw:
 
         return capi_data_str
 
+    def __iter__(self):
+        """Make this iterable on its raw_data dict."""
+        yield from self.raw_data
+
+    def __getitem__(self, item):
+        """Make the raw_data dict's items get'able."""
+        return self.raw_data.get(item)
+
 
 def listify(thing: Union[List, Dict]) -> List:
     """
diff --git a/stats.py b/stats.py
index 74f28e9c..89e79d9a 100644
--- a/stats.py
+++ b/stats.py
@@ -1,5 +1,6 @@
 """CMDR Status information."""
 import csv
+import json
 import tkinter
 import tkinter as tk
 from sys import platform
@@ -276,46 +277,40 @@ class StatsDialog():
             return
 
         # TODO: This needs to use cached data
-        # LANG: Fetching data from Frontier CAPI in order to display on File > Status
-        self.status['text'] = _('Fetching data...')
-        self.parent.update_idletasks()
-
-        try:
-            # TODO: This should use cached data
-            data = companion.session.profile()
-
-        except companion.ServerError as e:
-            self.status['text'] = str(e)
+        if companion.session.FRONTIER_CAPI_PATH_PROFILE not in companion.session.capi_raw_data:
+            logger.info('No cached data, aborting...')
             return
 
-        except Exception as e:
-            logger.exception("error while attempting to show status")
-            self.status['text'] = str(e)
-            return
+        capi_data = json.loads(
+            companion.session.capi_raw_data[companion.session.FRONTIER_CAPI_PATH_PROFILE].raw_data
+        )
 
-        if not data.get('commander') or not data['commander'].get('name', '').strip():
+        if not capi_data.get('commander') or not capi_data['commander'].get('name', '').strip():
             # Shouldn't happen
             # LANG: Unknown commander
             self.status['text'] = _("Who are you?!")
 
         elif (
-            not data.get('lastSystem')
-            or not data['lastSystem'].get('name', '').strip()
-            or not data.get('lastStarport')
-            or not data['lastStarport'].get('name', '').strip()
+            not capi_data.get('lastSystem')
+            or not capi_data['lastSystem'].get('name', '').strip()
+            or not capi_data.get('lastStarport')
+            or not capi_data['lastStarport'].get('name', '').strip()
         ):
             # Shouldn't happen
             # LANG: Unknown location
             self.status['text'] = _("Where are you?!")
 
-        elif not data.get('ship') or not data['ship'].get('modules') or not data['ship'].get('name', '').strip():
+        elif (
+            not capi_data.get('ship') or not capi_data['ship'].get('modules')
+            or not capi_data['ship'].get('name', '').strip()
+        ):
             # Shouldn't happen
             # LANG: Unknown ship
             self.status['text'] = _("What are you flying?!")
 
         else:
             self.status['text'] = ''
-            StatsResults(self.parent, data)
+            StatsResults(self.parent, capi_data)
 
 
 class StatsResults(tk.Toplevel):