// 本脚本只在不存在时会生成一次。已存在不会再次生成覆盖

using UnityEngine;
using NBC;
using NBF.Setting;
using UnityEngine.InputSystem;

namespace NBF
{
    public partial class SettingWaitInputPanel : UIPanel
    {
        private SettingItem _settingItem;
        private InputOption _inputOption;
        private InputActionRebindingExtensions.RebindingOperation rebindingOperation;
        private int _time;

        protected override void OnInit()
        {
            IsModal = true;
            BtnCancel.onClick.Set(Hide);
        }

        protected override void OnShow()
        {
            _time = 5;
            Timer.Loop(1, this, OnTimer);
            TextTime.text = _time.ToString();
            _settingItem = GetData() as SettingItem;
            if (_settingItem == null)
            {
                Hide();
                return;
            }

            if (_settingItem.Option is InputOption inputOption)
            {
                _inputOption = inputOption;
                OnRebinding();
            }
        }

        private void OnTimer()
        {
            _time--;
            TextTime.text = _time.ToString();
            if (_time <= 0)
            {
                OnBack();
            }
        }

        #region 按键绑定

        private void OnRebinding()
        {
            _inputOption.InputAction.Disable();
            // 开始重绑定操作
            rebindingOperation = _inputOption.InputAction.PerformInteractiveRebinding(_inputOption.BindingIndex)
                .OnMatchWaitForAnother(0.1f)
                .WithCancelingThrough("<Keyboard>/escape")
                .WithControlsExcluding("<Pointer>/press")
                .WithControlsExcluding("<Mouse>/press")
                .WithControlsExcluding("<Mouse>/leftButton")
                .WithControlsExcluding("<Mouse>/rightButton")
                .OnComplete(operation => RebindComplete())
                .OnCancel(operation => OnRebindCanceled())
                .Start();
        }

        private void RebindComplete()
        {
            var bindings = _inputOption.InputAction.bindings;
            for (int i = 0; i < bindings.Count; i++)
            {
                var bin = bindings[i];
                Log.Info($"RebindComplete==={bin.path}");
            }

            rebindingOperation.Dispose();
            _inputOption.InputAction.Enable();
            UpdateValueText();
        }

        private void OnRebindCanceled()
        {
            rebindingOperation.Dispose();
            _inputOption.InputAction.Enable();
            Hide();
        }

        private void UpdateValueText()
        {
            _settingItem.UpdateValueText();
            Hide();
        }

        #endregion


        [InputInvoke(InputDef.UI.Back)]
        private void OnBack()
        {
            rebindingOperation.Cancel();
            Hide();
            Timer.ClearAll(this);
        }
    }
}