using System.Collections.Generic;
using Unity.VisualScripting;
using UnityEngine;

public class BubbleSticky : Bubble
{
    public float stickAfter = 0.1f;

    public List<FixedJoint> joints = new();

    protected override void Update()
    {
        base.Update();
        for (int i = joints.Count - 1; i >= 0; i--)
        {
            if (joints[i].connectedBody == null)
            {
                Destroy(joints[i]);
                joints.RemoveAt(i);
                continue;
            }

            if (joints[i].connectedBody.isKinematic)
            {
                var bubble = joints[i].connectedBody.GetComponentInParent<BubbleContainer>();
                Destroy(joints[i]);
                joints.RemoveAt(i);
                if (bubble != null)
                {
                    var joint = gameObject.AddComponent<FixedJoint>();
                    joint.connectedBody = bubble.rb;
                    joints.Add(joint);
                }
            }
        }
    }

    private void OnTriggerEnter(Collider collider)
    {
        var time = Time.time - startTime;
        if (time < stickAfter && collider.attachedRigidbody?.GetComponent<BubbleSticky>() != null)
            return;

        var stickable = collider.attachedRigidbody?.GetComponent<Stickable>();
        if (stickable != null && collider.attachedRigidbody != null)
        {
            var otherJoint = joints.Find(e => e?.connectedBody == collider.attachedRigidbody);
            if (otherJoint == null)
            {
                var joint = gameObject.AddComponent<FixedJoint>();
                joint.connectedBody = collider.attachedRigidbody;
                joints.Add(joint);
            }
        }
    }
}