using RopeToolkit;
using System.Collections;
using System.Collections.Generic;
using Unity.VisualScripting;
using UnityEngine;
using UnityEngine.TextCore.Text;

public class CharacterRope : MonoBehaviour
{
    public Rope rope;
    public RopeConnection conn1, conn2;

    public Character target1;
    public Character target2;

    private void Awake()
    {
        RopeConnection[] conns = rope.GetComponents<RopeConnection>();
        conn1 = conns[0];
        conn2 = conns[1];
    }

    public void BeLink(Character character1, Character character2, bool addJoint = true)
    {
        transform.position = Vector3.zero;
        target1 = character1;
        target2 = character2;
        conn1.transformSettings.transform = character1.transform;
        conn2.transformSettings.transform = character2.transform;
        conn1.rigidbodySettings.body = character1.GetComponent<Rigidbody>();
        conn2.rigidbodySettings.body = character2.GetComponent<Rigidbody>();
        rope.spawnPoints.Clear();
        rope.spawnPoints.Add(character1.transform.position);
        rope.spawnPoints.Add(character2.transform.position);
        rope.gameObject.SetActive(true);
        character1.linked = true;
        if (addJoint)
        {
            if (!character1.joint)
            {
                character1.joint = character1.AddComponent<RopeJoint>();
            }
            character1.joint.rb = character1.rb;
            character1.joint.connectedBody = character2.rb;
            character1.joint.maxDistance = (character1.transform.position - character2.transform.position).magnitude;
            character1.rope = this;
        }
    }

    private void FixedUpdate()
    {
        if ((!target1 || target1.isDie) || (!target2 || target2.isDie))
        {
            gameObject.SetActive(false);
        }
    }
}
