Neighbourhood.omg.lol/Models/State.cs

76 lines
3 KiB
C#
Raw Normal View History

using System;
using System.Collections.Generic;
2024-06-05 12:41:08 +00:00
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<string>? AddressNames { get => AddressList?.Select(a => a.Address); }
public AddressResponseData? SelectedAddress { get; set; }
public string? SelectedAddressName { get => SelectedAddress?.Address; }
2024-06-05 12:41:08 +00:00
public List<Status>? 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<AccountResponseData>(accountJson);
if (!string.IsNullOrEmpty(addressJson)) AddressList = JsonSerializer.Deserialize<AddressResponseList>(addressJson);
if (!string.IsNullOrEmpty(selectedAddressJson)) SelectedAddress = JsonSerializer.Deserialize<AddressResponseData>(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));
}
}
}
2024-06-05 12:41:08 +00:00
public async Task RemoveAccountDetails() {
Preferences.Default.Clear();
AccountInfo = null;
AddressList = null;
SelectedAddress = null;
}
public async Task<Status[]?> 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();
}
}
}