using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text; using System.Text.Json; using System.Threading.Tasks; namespace Neighbourhood.omg.lol.Models { public class State { public AccountResponseData? AccountInfo { get; set; } public AddressResponseList? AddressList { get; set; } public string? Name { get => AccountInfo?.Name; } public string? Email { get => AccountInfo?.Email; } public IEnumerable? AddressNames { get => AddressList?.Select(a => a.Address); } public AddressResponseData? SelectedAddress { get; set; } public string? SelectedAddressName { get => SelectedAddress?.Address; } public List? Statuses { get; set; } public async Task PopulateAccountDetails(string token) { RestService api = new RestService(token); string accountJson = Preferences.Default.Get("accountdetails", string.Empty); string addressJson = Preferences.Default.Get("accountaddresses", string.Empty); string selectedAddressJson = Preferences.Default.Get("selectedaddress", string.Empty); if (!string.IsNullOrEmpty(accountJson)) AccountInfo = JsonSerializer.Deserialize(accountJson); if (!string.IsNullOrEmpty(addressJson)) AddressList = JsonSerializer.Deserialize(addressJson); if (!string.IsNullOrEmpty(selectedAddressJson)) SelectedAddress = JsonSerializer.Deserialize(selectedAddressJson); // if we haven't got account info, attempt to retrieve it. if (AccountInfo == null) { AccountInfo = await api.AccountInfo(); if (AccountInfo != null) { Preferences.Default.Set("accountdetails", JsonSerializer.Serialize(AccountInfo)); } } // if we don't have the list of addresses, attempt to retrieve that. if (AddressList == null) { AddressList = await api.Addresses(); if (AddressList != null) { Preferences.Default.Set("accountaddresses", JsonSerializer.Serialize(AddressList)); SelectedAddress = AddressList.FirstOrDefault(); Preferences.Default.Set("selectedaddress", JsonSerializer.Serialize(SelectedAddress)); } } } public async Task RemoveAccountDetails() { Preferences.Default.Clear(); AccountInfo = null; AddressList = null; SelectedAddress = null; } public async Task GetStatuses(bool forceRefresh = false) { RestService api = new RestService(); if (forceRefresh || this.Statuses == null || this.Statuses.Count == 0) { Debug.WriteLine("Downloading statuses from server"); this.Statuses = await api.StatuslogLatest(); } //else Task.Run(async () => this.Statuses = await api.StatuslogLatest()); // not awaited on purpose return this.Statuses.ToArray(); } public async Task RefreshStatuses() { RestService api = new RestService(); this.Statuses = await api.StatuslogLatest(); } } }