// Copyright © Selmo Technology GmbH. All Rights Reserved

using Microsoft.AspNetCore.Components;
using Microsoft.Extensions.Localization;
using SelmoStudio.Hmi.Server.Alarms.Model;
using SelmoStudio.Hmi.Server.Alarms.Service;
using SelmoStudio.Hmi.Server.SelmoHmi.Authentication.Components;
using SelmoStudio.Hmi.Server.SelmoHmi.Authentication.Service;
using SelmoStudio.Hmi.Server.SelmoHmi.Dialog.Service;
using SelmoStudio.Hmi.Server.Shared.Resources;
using System.Timers;

namespace SelmoStudio.Hmi.Server.Header.Components
{
    public partial class SelmoHeader : IDisposable
    {
        private System.Timers.Timer _timer = null!;
        private string _time = "";
        private string _dateInfo = "";
        private Alarm _headerAlarm;

        private IHmiDialogService _loginDialogService;

        [Inject]
        private IStringLocalizer<HmiResource> _localizer { get; set; }

        [Inject]
        private IAlarmService _alarmService { get; set; }

        [Inject]
        private IDialogService _dialogService { get; set; }

        [Inject]
        private IAuthenticationStateService _authenticationStateService { get; set; }

        protected override async Task OnInitializedAsync()
        {
            _loginDialogService = new HmiDialogService(_dialogService, "LoginDialog");

            _alarmService.OnUpdate += async () => await OnUpdate();
            await UpdateHeaderAlarm();

            _timer = new System.Timers.Timer(1000);
            _timer.Elapsed += OnTimedEvent;
            _timer.AutoReset = true;
            _timer.Start();

            await base.OnInitializedAsync();
        }

        private async void OnTimedEvent(object? sender, ElapsedEventArgs e)
        {
            _time = GetCurrentTime();
            _dateInfo = GetCurrentDateInfo();

            await InvokeAsync(() =>
            {
                StateHasChanged();
            });
        }

        private async Task OnUpdate()
        {
            await UpdateHeaderAlarm();

            await InvokeAsync(() => StateHasChanged());
        }

        private async Task UpdateHeaderAlarm()
        {
            _headerAlarm = await _alarmService.HeaderAlarm;
        }

        private string GetCurrentDateInfo()
        {
            return $"{Thread.CurrentThread.CurrentCulture.DateTimeFormat.GetDayName(DateTime.Today.DayOfWeek)}, {DateTime.Now.Date.Day.ToString()}"
            + $".{DateTime.Now.Date.Month.ToString()}.{DateTime.Now.Date.Year.ToString()}";
        }

        private string GetCurrentTime()
        {
            return $"{DateTime.Now.ToString("H:mm:ss")}";
        }

        private async Task ShowAuthenticationDialog()
        {
            // TODO If user is not logged in, show the login dialog, otherwise show the log out dialog
            await _loginDialogService.OpenDialogAsync<AuthenticationComponent>(@_localizer[nameof(HmiResource.Login)], "550px", "270px",
                new Dictionary<string, object>() { { "OnAuthenticated", EventCallback.Factory.Create(this, OnAuthenticated) } });
        }

        private async Task OnAuthenticated()
        {
            _loginDialogService.CloseDialog();

            await _authenticationStateService.NotifyAuthenticationStateChangedAsync();
        }

        public void Dispose()
        {
            if (_timer != null && _timer.Enabled)
            {
                _timer.Stop();
                _timer.Elapsed -= OnTimedEvent;
                _timer.Dispose();
            }

            if (_loginDialogService != null)
            {
                ((HmiDialogService)_loginDialogService).Dispose();
            }
        }
    }
}