ViewModelBase.cs 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Diagnostics.CodeAnalysis;
  4. using System.Linq;
  5. using System.Reflection;
  6. using System.Threading;
  7. using System.Threading.Tasks;
  8. using Avalonia.Svg.Skia;
  9. using Avalonia.Threading;
  10. using Comal.Classes;
  11. using CommunityToolkit.Mvvm.ComponentModel;
  12. using CommunityToolkit.Mvvm.Input;
  13. using DialogHostAvalonia;
  14. using InABox.Avalonia;
  15. using InABox.Avalonia.Components;
  16. using InABox.Configuration;
  17. using InABox.Core;
  18. using PRS.Avalonia.Components;
  19. using PRS.Avalonia.Dialogs;
  20. namespace PRS.Avalonia;
  21. public abstract partial class ViewModelBase : ObservableValidator, IViewModelBase
  22. {
  23. private static DataAccessLayer? _dataAccessLayer;
  24. private static RepositoryLayer? _repositories;
  25. private static Dictionary<string, MobileDatabaseSettings>? _databaseSettings;
  26. private static MobileDatabaseSettings? _currentDatabase;
  27. [ObservableProperty] private bool _backButtonVisible = true;
  28. private CancellationTokenSource _cts = new();
  29. [ObservableProperty] private AvaloniaMenuItemCollection _primaryMenu = new();
  30. [ObservableProperty] private bool _reverseTransition;
  31. [ObservableProperty] private AvaloniaMenuItemCollection _secondaryMenu = new();
  32. [ObservableProperty]
  33. private bool _progressVisible = false;
  34. public static DataAccessLayer DataAccess
  35. {
  36. get
  37. {
  38. if (_dataAccessLayer == null)
  39. {
  40. _dataAccessLayer = new DataAccessLayer();
  41. _dataAccessLayer.Connected += (s, e) => Connected();
  42. _dataAccessLayer.Disconnected += (s, e) => Disconnected();
  43. _dataAccessLayer.Validated += (s, e) => Validated();
  44. }
  45. _dataAccessLayer ??= new DataAccessLayer();
  46. return _dataAccessLayer;
  47. }
  48. }
  49. public static RepositoryLayer Repositories
  50. {
  51. get
  52. {
  53. _repositories ??= new RepositoryLayer(DataAccess);
  54. return _repositories;
  55. }
  56. }
  57. public static Dictionary<string, MobileDatabaseSettings> DatabaseSettings
  58. {
  59. get
  60. {
  61. if (_databaseSettings == null)
  62. LoadDatabaseSettings();
  63. return _databaseSettings;
  64. }
  65. }
  66. public static MobileDatabaseSettings CurrentDatabase
  67. {
  68. get
  69. {
  70. if (_currentDatabase == null)
  71. LoadDatabaseSettings();
  72. return DatabaseSettings.Any(x => x.Value.IsDefault)
  73. ? DatabaseSettings.FirstOrDefault(x => x.Value.IsDefault).Value
  74. : DatabaseSettings.First().Value;
  75. }
  76. }
  77. public static string CurrentDatabaseName => DatabaseSettings.Any(x => x.Value.IsDefault)
  78. ? DatabaseSettings.FirstOrDefault(x => x.Value.IsDefault).Key
  79. : DatabaseSettings.First().Key;
  80. public static bool IsSharedDevice =>
  81. string.IsNullOrWhiteSpace(CurrentDatabase.UserID)
  82. || string.IsNullOrWhiteSpace(CurrentDatabase.Password);
  83. private static void Connected()
  84. {
  85. }
  86. private static void Validated()
  87. {
  88. Repositories.MeModel.Refresh(true);
  89. }
  90. private static void Disconnected()
  91. {
  92. }
  93. public string DefaultCacheFileName<T>(Guid? id = null, string? tag = null) where T : IShell
  94. {
  95. return string.IsNullOrWhiteSpace(tag)
  96. ? id == null
  97. ? $"{GetType().Name}.{typeof(T).Name}"
  98. : $"{GetType().Name}.{typeof(T).Name}.{id}"
  99. : id == null
  100. ? $"{GetType().Name}.{typeof(T).Name}-{tag}"
  101. : $"{GetType().Name}.{typeof(T).Name}-{tag}.{id}";
  102. }
  103. [RelayCommand]
  104. private void BackButtonPressed()
  105. {
  106. if (OnBackButtonPressed())
  107. Navigation.Back();
  108. }
  109. public virtual bool OnBackButtonPressed()
  110. {
  111. return true;
  112. }
  113. public async Task Activate()
  114. {
  115. await OnActivated();
  116. var token = _cts.Token;
  117. _ = Task.Run(
  118. async () =>
  119. {
  120. var result = await Refresh();
  121. while (result != TimeSpan.Zero)
  122. {
  123. if (token.IsCancellationRequested)
  124. break;
  125. await Task.Delay(result);
  126. if (!token.IsCancellationRequested)
  127. result = await Refresh();
  128. }
  129. },
  130. token
  131. ).ContinueWith(task =>
  132. {
  133. if(task.Exception is not null)
  134. {
  135. App.HandleException(task.Exception);
  136. }
  137. });
  138. }
  139. protected virtual Task OnActivated()
  140. {
  141. return Task.CompletedTask;
  142. }
  143. private async Task<TimeSpan> Refresh()
  144. {
  145. return await OnRefresh();
  146. }
  147. /// <summary>
  148. /// Refresh the data on the screen. If this method returns a value other than <see cref="TimeSpan.Zero"/>, then that value is used to
  149. /// schedule the next refresh.
  150. /// </summary>
  151. /// <returns>Time until next refresh is triggered, or <see cref="TimeSpan.Zero"/> if periodic refreshing is unwanted.</returns>
  152. protected virtual Task<TimeSpan> OnRefresh()
  153. {
  154. return Task.FromResult(TimeSpan.FromSeconds(30));
  155. }
  156. public async Task Deactivate()
  157. {
  158. await _cts.CancelAsync();
  159. _cts.Dispose();
  160. _cts = new CancellationTokenSource();
  161. await OnDeactivated();
  162. await Task.CompletedTask;
  163. }
  164. protected virtual Task OnDeactivated()
  165. {
  166. return Task.CompletedTask;
  167. }
  168. public static void SaveDatabaseSettings()
  169. {
  170. var config = new LocalConfiguration<MobileDatabaseSettings>();
  171. var old = config.LoadAll();
  172. foreach (var key in old.Keys)
  173. if (!DatabaseSettings.ContainsKey(key))
  174. new LocalConfiguration<MobileDatabaseSettings>(key).Delete();
  175. config.SaveAll(DatabaseSettings);
  176. }
  177. [MemberNotNull(nameof(_databaseSettings))]
  178. public static void LoadDatabaseSettings()
  179. {
  180. _databaseSettings = new LocalConfiguration<MobileDatabaseSettings>().LoadAll();
  181. // Contruct Defaults if required
  182. if (!_databaseSettings.Any())
  183. {
  184. _currentDatabase = new MobileDatabaseSettings();
  185. _currentDatabase.URLs = new[]
  186. {
  187. "demo.prsdigital.com.au:8033"
  188. };
  189. _currentDatabase.UserID = "GUEST";
  190. _currentDatabase.Password = "guest";
  191. _currentDatabase.IsDefault = true;
  192. _currentDatabase.CacheID = Guid.NewGuid();
  193. _databaseSettings["Demo Database"] = _currentDatabase;
  194. new LocalConfiguration<MobileDatabaseSettings>().SaveAll(_databaseSettings);
  195. }
  196. // Retrieve the Default (or the first, if there is no default)
  197. _currentDatabase = _databaseSettings.Any(x => x.Value.IsDefault)
  198. ? _databaseSettings.FirstOrDefault(x => x.Value.IsDefault).Value
  199. : _databaseSettings.First().Value;
  200. if (_currentDatabase.CacheID == Guid.Empty)
  201. {
  202. _currentDatabase.CacheID = Guid.NewGuid();
  203. new LocalConfiguration<MobileDatabaseSettings>().SaveAll(_databaseSettings);
  204. }
  205. }
  206. }
  207. public abstract class PopupViewModel : ViewModelBase, IPopupViewModel
  208. {
  209. public bool IsClosed { get; private set; }
  210. public void Close()
  211. {
  212. IsClosed = true;
  213. DialogHost.GetDialogSession(null)?.Close();
  214. }
  215. }
  216. public abstract class PopupViewModel<TResult> : PopupViewModel, IPopupViewModel<TResult>
  217. {
  218. private TResult? _result;
  219. public TResult? GetResult()
  220. {
  221. return _result ?? default;
  222. }
  223. public void Close(TResult result)
  224. {
  225. _result = result;
  226. Close();
  227. }
  228. }