| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182 |
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Threading.Tasks;
- using CaritasPWA.Shared.Models;
- using Microsoft.JSInterop;
-
- namespace CaritasPWA.Shared {
- public class MasterDataService {
-
- private const string KeyNameColors = "colors";
- private const string KeyNameBcTypes = "bicycleTypes";
-
- private readonly IJSRuntime _jsRuntime;
- private bool _initializedColors;
- private ColorItem[] _colors = new ColorItem[] { };
-
- public ColorItem[] Colors {
- get => _colors;
- set => _colors = value;
- }
-
- public event EventHandler Changed;
-
- public MasterDataService(IJSRuntime jsRuntime) {
- _jsRuntime = jsRuntime;
- }
-
- public async Task SynchronizeColors() {
- // TODO: Get the color from server via REST and save it when not empty
- _colors = Defaults.ColorItems;
- await SaveColorsToStorage();
- }
-
- public async Task<ColorItem[]> GetColors() {
- // To search first in local storage, when nothing is found return the defaults.
- //return Defaults.ColorItems;
- return await GetColorsFromStorage();
- }
-
- private async ValueTask<ColorItem[]> GetColorsFromStorage() {
-
- // Register the Storage event handler. This handler calls OnStorageUpdated when the storage changed.
- // This way, you can reload the settings when another instance of the application (tab / window) save the settings
- if (!_initializedColors) {
- // Create a reference to the current object, so the JS function can call the public method "OnStorageUpdated"
- var reference = DotNetObjectReference.Create(this);
- await _jsRuntime.InvokeVoidAsync("BlazorRegisterStorageEvent", reference);
- _initializedColors = true;
- }
-
- // Read the JSON string that contains the data from the local storage
- ColorItem[] result;
- var str = await _jsRuntime.InvokeAsync<string>("BlazorGetLocalStorage", KeyNameColors);
- if (str != null) {
- result = System.Text.Json.JsonSerializer.Deserialize<ColorItem[]>(str) ?? new ColorItem[] { };
- } else {
- result = new ColorItem[] { };
- }
- _colors= result;
- return result;
- }
-
- private async Task SaveColorsToStorage() {
- var json = System.Text.Json.JsonSerializer.Serialize(_colors);
- await _jsRuntime.InvokeVoidAsync("BlazorSetLocalStorage", KeyNameColors, json);
- }
-
- // This method is called from BlazorRegisterStorageEvent when the storage changed
- [JSInvokable]
- public void OnStorageUpdated(string key) {
- // Reset the settings. The next call to Get will reload the data
- if (key == KeyNameColors) {
- _colors = null;
- Changed?.Invoke(this, EventArgs.Empty);
- } else if (key == KeyNameBcTypes) {
- //_bicycleType = null;
- Changed?.Invoke(this, EventArgs.Empty);
- }
- }
- }
- }
|