using UnityEngine;

namespace NBF.TEST
{
    public class NodeNodeTest : MonoBehaviour
    {
        [Header("Input")] [SerializeField] private KeyCode extendKey = KeyCode.UpArrow;
        [SerializeField] private KeyCode retractKey = KeyCode.DownArrow;
        [SerializeField] private FishingLineNode rope = null;
        [SerializeField] private FLine line = null;

        [Header("Length Change")] [Min(0.001f)] [SerializeField]
        private float clickLengthDelta = 0.1f;

        [Min(0f)] [SerializeField] private float longPressThreshold = 0.25f;
        [Min(0f)] [SerializeField] private float holdLengthDeltaPerSecond = 0.8f;

        private float _extendPressTime = -1f;
        private float _retractPressTime = -1f;

        private void Update()
        {
            if (!rope) return;

            HandleLengthInput(extendKey, true, ref _extendPressTime);
            HandleLengthInput(retractKey, false, ref _retractPressTime);

            if (Input.GetKeyDown(KeyCode.Alpha1))
            {
                rope.SetLenght(1);
            }

            if (Input.GetKeyDown(KeyCode.Alpha2))
            {
                rope.SetLenght(2);
            }

            if (Input.GetKeyDown(KeyCode.Alpha3))
            {
                rope.SetLenght(3);
            }
            if (Input.GetKeyDown(KeyCode.Alpha8))
            {
                line.SetRopeLimit(!line.IsRopeLimit);
            }
            if (Input.GetKeyDown(KeyCode.Alpha9))
            {
                rope.Rope.Print();
            }
            
            if (line.CurrentBreakStretchPercent > 10)
            {
                // Debug.LogError($"当前极限情况，CurrentBreakStretchPercent={line.CurrentBreakStretchPercent} CurrentStretchLength={line.CurrentStretchLength} Len={line.TotalLength} LimitStateTime={line.LimitStateTime}");
            }
        }

        private void HandleLengthInput(KeyCode key, bool isExtend, ref float pressTime)
        {
            if (Input.GetKeyDown(key))
            {
                pressTime = Time.time;
                ApplyLengthDelta(isExtend ? clickLengthDelta : -clickLengthDelta);
            }

            if (Input.GetKey(key) && pressTime >= 0f)
            {
                var heldTime = Time.time - pressTime;
                if (heldTime >= longPressThreshold && holdLengthDeltaPerSecond > 0f)
                {
                    var delta = holdLengthDeltaPerSecond * Time.deltaTime;
                    ApplyLengthDelta(isExtend ? delta : -delta);
                }
            }

            if (Input.GetKeyUp(key))
                pressTime = -1f;
        }

        private void ApplyLengthDelta(float delta)
        {
            if (delta > 0f)
            {
                // rope.IncreaseLength(delta);
                rope.SetLenght(rope.Lenght + delta);
                return;
            }

            if (delta < 0f)
            {
                rope.SetLenght(rope.Lenght + delta);
            }
        }
    }
}