using RootMotion.FinalIK;
using UnityEngine;

public class FFishRagDoll : MonoBehaviour
{
    private Transform TailRag;

    [HideInInspector]
    public CCDIK _ccidk;

    private FFish fish;

    private void Start()
    {
        fish = GetComponent<FFish>();
        _ccidk = GetComponent<CCDIK>();
        TailRag = _ccidk.solver.target;
        if (TailRag == null)
        {
            Debug.LogError("Ryba nie ma podczepionego TailRag: " + transform.name);
        }
        else
        {
            SetupTailRag();
        }
    }

    private void SetupTailRag()
    {
        TailRag.GetComponent<SpringJoint>().maxDistance = transform.localScale.z * 0.2f;
        TailRag.GetComponent<SpringJoint>().connectedBody = GetComponent<Rigidbody>();
        TailRag.GetComponent<Rigidbody>().linearDamping = 0.2f;
        _ccidk.enabled = false;
    }

    private void Update()
    {
        if (TailRag == null)
        {
            if (_ccidk == null || _ccidk.solver.target == null)
            {
                return;
            }
            TailRag = _ccidk.solver.target;
            SetupTailRag();
        }
        if (fish.isGetFish && TailRag.parent == transform)
        {
            TailRag.transform.SetParent(transform.parent);
        }
        if (transform.position.y > 0f)
        {
            _ccidk.enabled = true;
            if (fish.isFishView)
            {
                _ccidk.solver.IKPositionWeight = 0.05f * transform.localScale.z;
            }
            else
            {
                _ccidk.solver.IKPositionWeight = Mathf.Clamp(transform.position.y, 0f, 1f);
            }
            TailRag.gameObject.SetActive(value: true);
        }
        else if (transform.position.y < 0f && TailRag.gameObject.activeSelf)
        {
            _ccidk.enabled = false;
            if (TailRag.parent != transform)
            {
                TailRag.transform.SetParent(transform);
            }
            TailRag.gameObject.SetActive(value: false);
        }
    }

    private void OnDestroy()
    {
        if (!(TailRag == null))
        {
            Destroy(TailRag.gameObject);
        }
    }
}