using System.Text.Json;
using Microsoft.JSInterop;

namespace FoodsharingSiegen.Server.Service
{
    /// <summary>
    /// The local storage service class (a. beging, 02.04.2022)
    /// </summary>
    public class LocalStorageService
    {
        #region Private Fields

        /// <summary>
        /// The js runtime
        /// </summary>
        private readonly IJSRuntime _jsRuntime;

        #endregion

        #region Setup/Teardown

        /// <summary>
        ///     Constructor
        /// </summary>
        /// <param name="jsRuntime"></param>
        public LocalStorageService(IJSRuntime jsRuntime) => _jsRuntime = jsRuntime;

        #endregion

        #region Public Method GetItem

        /// <summary>
        ///     Ein Item aus dem LocalStorage laden
        /// </summary>
        /// <param name="key">Der Key des Items</param>
        /// <typeparam name="T">Typ des Item</typeparam>
        /// <returns></returns>
        public async Task<T?> GetItem<T>(string key)
        {
            var json = await _jsRuntime.InvokeAsync<string>("localStorage.getItem", key);

            if (json == null)
                return default;

            return JsonSerializer.Deserialize<T>(json);
        }

        #endregion

        #region Public Method RemoveItem
        
        /// <summary>
        ///     Ein Item aus dem LocalStorage löschen
        /// </summary>
        /// <param name="key">Der Key des Items</param>
        public async Task RemoveItem(string key)
        {
            await _jsRuntime.InvokeVoidAsync("localStorage.removeItem", key);
        }
        
        #endregion

        #region Public Method SetItem
        
        /// <summary>
        ///     Ein Item in den LocalStorage schreiben
        /// </summary>
        /// <param name="key">Der Key des Items</param>
        /// <param name="value">Das Item</param>
        /// <typeparam name="T">Typ des Item</typeparam>
        public async Task SetItem<T>(string key, T value)
        {
            await _jsRuntime.InvokeVoidAsync("localStorage.setItem", key, JsonSerializer.Serialize(value));
        }

        #endregion
    }
}