﻿using UnityEngine;

namespace NBF
{
    public class FishingLineTestController : MonoBehaviour
    {
        [Header("References")] [SerializeField]
        private FishingLineSolver solver;

        [Header("Length Test")] [Min(0f)] [SerializeField]
        private float initialFirstSegmentLength = 1.2f;

        [Min(0f)] [SerializeField] private float minFirstSegmentLength = 0.1f;
        [Min(0f)] [SerializeField] private float maxFirstSegmentLength = 5f;
        [Min(0f)] [SerializeField] private float lineAdjustSpeed = 1f;

        [Header("Input")] [SerializeField] private KeyCode extendKey = KeyCode.UpArrow;
        [SerializeField] private KeyCode retractKey = KeyCode.DownArrow;

        private float targetFirstSegmentLength;

        private void Reset()
        {
            if (solver == null)
            {
                solver = GetComponent<FishingLineSolver>();
            }
        }

        private void Start()
        {
            if (solver == null)
            {
                return;
            }

            targetFirstSegmentLength =
                Mathf.Clamp(initialFirstSegmentLength, minFirstSegmentLength, maxFirstSegmentLength);
            solver.SetLenght(targetFirstSegmentLength);
            solver.SetLenght(0.5f, 1);
            // solver.BuildLine();

            solver.OnLineBreakRequested += OnLineBreakRequested;
        }

        private void OnLineBreakRequested(FishingLineSolver lineSolver)
        {
            Debug.LogError($"当前拉力达到极限，切线，极限时间={lineSolver.LimitStateTime}");
            var endNode = lineSolver.GetEndNode();
            if (endNode != null)
            {
                endNode.Body.isKinematic = false;
            }
        }

        private void Update()
        {
            if (solver == null)
            {
                return;
            }

            var input = 0f;
            if (Input.GetKey(extendKey))
            {
                input += 1f;
            }

            if (Input.GetKey(retractKey))
            {
                input -= 1f;
            }

            if (!Mathf.Approximately(input, 0f))
            {
                targetFirstSegmentLength += input * lineAdjustSpeed * Time.deltaTime;
                targetFirstSegmentLength =
                    Mathf.Clamp(targetFirstSegmentLength, minFirstSegmentLength, maxFirstSegmentLength);
                solver.SetLenght(targetFirstSegmentLength);
            }

            if (solver.CurrentBreakStretchPercent > 10)
            {
                Debug.LogError($"当前极限情况，CurrentBreakStretchPercent={solver.CurrentBreakStretchPercent} CurrentStretchLength={solver.CurrentStretchLength} LimitStateTime={solver.LimitStateTime}");
            }
        }
    }
}
