using UnityEngine;
using UnityEngine.InputSystem;

namespace NBF.Setting
{
    public abstract class InputOption : OptionBase
    {
        private int _bindingIndex = 0;
        public abstract InputAction InputAction { get; }

        public int BindingIndex => _bindingIndex;

        protected override int DefaultValue => 0;

        /// <summary>
        /// 保存的值
        /// </summary>
        protected string InputSaveValue;

        public override bool HaveNotApple()
        {
            return !InputAction.SaveBindingOverridesAsJson().Equals(InputSaveValue);
        }

        public override void Apply()
        {
            // 保存绑定
            InputSaveValue = InputAction.SaveBindingOverridesAsJson();
            PlayerPrefs.SetString(SaveKey, InputSaveValue);
            OnApply();
        }

        public override void Load()
        {
            for (int i = 0; i < InputAction.bindings.Count; i++)
            {
                var binding = InputAction.bindings[i];
                if (IsBindingContains(binding))
                {
                    _bindingIndex = i;
                    break;
                }
            }

            var value = PlayerPrefs.GetString(SaveKey, string.Empty);
            InputSaveValue = value;
            if (!string.IsNullOrEmpty(InputSaveValue))
            {
                InputAction.LoadBindingOverridesFromJson(InputSaveValue);
            }
        }

        public override void Reset()
        {
            if (InputAction.bindings[BindingIndex].isComposite)
            {
                // It's a composite. Remove overrides from part bindings.
                for (var i = BindingIndex + 1;
                     i < InputAction.bindings.Count && InputAction.bindings[i].isPartOfComposite;
                     ++i)
                    InputAction.RemoveBindingOverride(i);
            }
            else
            {
                InputAction.RemoveBindingOverride(BindingIndex);
            }
        }

        public override void Cancel()
        {
            if (!string.IsNullOrEmpty(InputSaveValue))
            {
                InputAction.LoadBindingOverridesFromJson(InputSaveValue);
            }
            else
            {
                Reset();
            }
        }

        public override string GetDisplayString()
        {
            if (InputAction != null)
            {
                return InputAction.GetBindingDisplayString(BindingIndex);
            }

            return base.GetDisplayString();
        }

        protected virtual bool IsBindingContains(InputBinding binding)
        {
            return true;
        }
    }
}