// Copyright © Selmo Technology GmbH. All Rights Reserved

using Microsoft.JSInterop;
using SelmoStudio.Hmi.Server.Shared.Components.Chart.Interfaces;
using System.Threading.Tasks;

namespace SelmoStudio.Hmi.Server.Shared.Components.Chart
{
    public class ChartJsInterop
    {
        private readonly Lazy<Task<IJSObjectReference>> moduleTask;

        public ChartJsInterop(IJSRuntime jsRuntime)
        {
            moduleTask = new(() => jsRuntime.InvokeAsync<IJSObjectReference>("import",
                "./Chart.js").AsTask());
        }

        public async ValueTask Setup(DotNetObjectReference<IChartConfig> dotNetObjectRef, IChartConfig Config)
        {
            var module = await moduleTask.Value;
            await module.InvokeVoidAsync("chartSetup", Config.CanvasId, dotNetObjectRef, Config);
        }

        public async ValueTask AddData(string CanvasId, List<string> labels, int datasetIndex, List<decimal?> data)
        {
            var module = await moduleTask.Value;
            await module.InvokeVoidAsync("addData", CanvasId, labels, datasetIndex, data);
        }

        public async ValueTask AddData(string CanvasId, int datasetIndex, decimal x, decimal y)
        {
            var module = await moduleTask.Value;
            await module.InvokeVoidAsync("addXYData", CanvasId, datasetIndex, x, y);
        }

        public async ValueTask AddDataWithRemoveFirst(string CanvasId, List<string> labels, List<decimal?> data)
        {
            var module = await moduleTask.Value;
            await module.InvokeVoidAsync("addDataWithRemoveFirst", CanvasId, labels, data);
        }

        public async ValueTask RemoveFirst(string CanvasId, int datasetIndex)
        {
            var module = await moduleTask.Value;
            await module.InvokeVoidAsync("removeFirst", CanvasId, datasetIndex);
        }

        public async ValueTask AddNewDataset<T>(string CanvasId, T dataset) where T : class
        {
            var module = await moduleTask.Value;
            await module.InvokeVoidAsync("addNewDataset", CanvasId, dataset);
        }

        public async ValueTask RemoveDataset(string CanvasId, int datasetIndex)
        {
            var module = await moduleTask.Value;
            await module.InvokeVoidAsync("removeDataset", CanvasId, datasetIndex);
        }

        public async ValueTask UpdateXScale(string CanvasId, decimal? min, decimal? max)
        {
            var module = await moduleTask.Value;
            await module.InvokeVoidAsync("updateXScale", CanvasId, min, max);
        }
    }
}