using System;
using Content.Shared.CCVar;
using Robust.Client.AutoGenerated;
using Robust.Client.Graphics;
using Robust.Client.UserInterface;
using Robust.Client.UserInterface.Controls;
using Robust.Client.UserInterface.XAML;
using Robust.Shared;
using Robust.Shared.Maths;
using Robust.Shared.Configuration;
using Robust.Shared.IoC;
using Robust.Shared.Localization;

namespace Content.Client.EscapeMenu.UI.Tabs
{
    [GenerateTypedNameReferences]
    public sealed partial class NetworkTab : Control
    {
        [Dependency] private readonly IConfigurationManager _cfg = default!;

        public NetworkTab()
        {
            RobustXamlLoader.Load(this);
            IoCManager.InjectDependencies(this);

            ApplyButton.OnPressed += OnApplyButtonPressed;
            ResetButton.OnPressed += OnResetButtonPressed;
            NetInterpRatioSlider.OnValueChanged += OnNetInterpRatioSliderChanged;

            Reset();
        }

        protected override void Dispose(bool disposing)
        {
            ApplyButton.OnPressed -= OnApplyButtonPressed;
            ResetButton.OnPressed -= OnResetButtonPressed;
            NetInterpRatioSlider.OnValueChanged -= OnNetInterpRatioSliderChanged;
            base.Dispose(disposing);
        }

        private void OnNetInterpRatioSliderChanged(Robust.Client.UserInterface.Controls.Range range)
        {
            UpdateChanges();
        }

        private void OnApplyButtonPressed(BaseButton.ButtonEventArgs args)
        {
            _cfg.SetCVar(CVars.NetInterpRatio, (int) NetInterpRatioSlider.Value);
            _cfg.SaveToFile();
            UpdateChanges();
        }

        private void OnResetButtonPressed(BaseButton.ButtonEventArgs args)
        {
            Reset();
        }

        private void Reset()
        {
            NetInterpRatioSlider.Value = _cfg.GetCVar(CVars.NetInterpRatio);
            UpdateChanges();
        }

        private void UpdateChanges()
        {
            var isEverythingSame = NetInterpRatioSlider.Value == _cfg.GetCVar(CVars.NetInterpRatio);
            ApplyButton.Disabled = isEverythingSame;
            ResetButton.Disabled = isEverythingSame;
            NetInterpRatioLabel.Text = NetInterpRatioSlider.Value.ToString();
        }
    }
}
