// Copyright © Selmo Technology GmbH. All Rights Reserved

using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Components.Authorization;
using Microsoft.AspNetCore.Components.Forms;
using Newtonsoft.Json;
using Novus.Connectivity.Common;
using Novus.Connectivity.Service;
using SelmoStudio.Hmi.Server.ProcessValue.Services;
using SelmoStudio.Hmi.Server.SelmoHmi.Shared.Model;
using SelmoStudio.Hmi.Server.SelmoHmi.Shared.Service;
using SelmoStudio.Hmi.Server.SelmoHmi.Shared.TestImpl;
using static SelmoStudio.Hmi.Server.SelmoHmi.Shared.TestImpl.TestValuesForDemo;

namespace SelmoStudio.Hmi.Server.Test_Page
{
    public partial class TestDataSetupPage : IDisposable
    {
        private string _gvlAdress = "GVL_Drilling_HMI.stHmiIf.iHmiMsgStepCounter";
        private string _pollingContent = "";
        private ValuesConnectionRegistration _registration;
        private TestProcessValueInfo _processValue = new();

        //GVL_Drilling_HMI.stHmiIf.iHmiMsgStepCounter
        private Int16 _fetchedValue = 0;

        [Inject]
        private IProcessValuePollingService _registrationService { get; set; }

        [Inject]
        private IProjectService _projectService { get; set; }

        [Inject]
        private IHttpContextAccessor _httpContextAccessor { get; set; }

        [Inject]
        private AuthenticationStateProvider _selmoAuthenticationStateProvider { get; set; }

        private void Register()
        {
            UpdateTestProcessValue();

            _registration = ValuesConnectionRegistration.Create(_processValue);
            _registrationService.RegisterValues(_registration);

            _registrationService.OnIntervalElapsed += IntervallEllapsed;
        }

        private void UpdateTestProcessValue()
        {
            _processValue = new TestProcessValueInfo()
            {
                Address = new TestValueConnectionAddress()
                {
                    ConnectionType = ConnectionType.Ads,
                    FullPath = _gvlAdress,
                    RelativePath = ""
                },
                DataType = typeof(System.Int16),
                Display = "test",
                Id = new(Guid.Parse("62749852-1f9e-4c12-a98c-979f11f045b8")),
                InitValue = false,
                Name = _gvlAdress
            };
        }

        private void WriteValue()
        {
            _registrationService.WriteValue(new TestValuesForDemo.TestProcessValue()
            {
                Value = _fetchedValue,
                ValueInfo = _processValue
            });
        }

        private void IntervallEllapsed(object sender, EventArgs e)
        {
            Task.Run(async () =>
            {
                var values = (await _registrationService.GetValues(_registration.Id)).Value;
                foreach (var value in values.ProcessValues)
                {
                    _fetchedValue = Convert.ToInt16(value.Value.Value.ToString());
                    _pollingContent = $"Content: {(_fetchedValue.ToString())}";
                }
                await InvokeAsync(() => StateHasChanged());
            });
        }

        protected override async Task OnInitializedAsync()
        {
            var context = _httpContextAccessor.HttpContext;
            var userName = _httpContextAccessor.HttpContext.User.Identity.Name != null ? _httpContextAccessor.HttpContext.User.Identity.Name : "---";
            var userInfo = $"Current User = {userName}";

            await base.OnInitializedAsync();
        }

        #region File Loading

        //private async void LoadFiles(InputFileChangeEventArgs e)
        //{
        //    await using FileStream fs = new(_projectService.ProjectFilePath, FileMode.Create);
        //    await e.File.OpenReadStream().CopyToAsync(fs);
        //    fs.Close();

        // _projectService.Reload(); var project = _projectService.GetProject();

        //    LoadParams(project);
        //    StateHasChanged();
        //}

        //private void LoadParams(SelmoHmiProject project)
        //{
        //    string parameterBaseFilePath = Path.Combine("./", "SelmoHmi", "Parameters");
        //    Directory.CreateDirectory(parameterBaseFilePath);

        // project.Plants.ForEach(p => { if (p.ParameterCollection.Count > 0) { string parameterFilePath =
        // Path.Combine(parameterBaseFilePath, p.ParameterCollection[0].Id.Guid.ToString() + ".json"); var processValues =
        // p.ParameterCollection[0].Parameters.Select(p => p.ProcessValueInfo); string parameterString = JsonConvert.SerializeObject(processValues);

        // File.WriteAllText(parameterFilePath, parameterString); } p.HardwareZones.ForEach(hw => { if
        // (hw.ParameterCollection.Count > 0) { string parameterFilePath = Path.Combine(parameterBaseFilePath,
        // hw.ParameterCollection[0].Id.Guid.ToString() + ".json"); var processValues =
        // hw.ParameterCollection[0].Parameters.Select(p => p.ProcessValueInfo); string parameterString = JsonConvert.SerializeObject(processValues);

        // File.WriteAllText(parameterFilePath, parameterString); } hw.Sequences.ForEach(seq => { string parameterFilePath =
        // Path.Combine(parameterBaseFilePath, seq.ParameterCollection.Id.Guid.ToString() + ".json"); var processValues =
        // seq.ParameterCollection.Parameters.Select(p => p.ProcessValueInfo); string parameterString = JsonConvert.SerializeObject(processValues);

        //                File.WriteAllText(parameterFilePath, parameterString);
        //            });
        //        });
        //    });
        //}

        public void Dispose()
        {
            if (_registration != null)
            {
                _registrationService.UnRegisterValues(_registration.Id);
                _registrationService.OnIntervalElapsed -= IntervallEllapsed;
            }
        }

        #endregion File Loading
    }
}