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

public class BubbleContainer : Bubble
{
    public float stickAfter = 0.1f;
    public float smooth = 10f;
    public Collider body;
    public Containable containable;

    public GameManager game => GameManager.instance;

    private bool destroyed;

    private void Awake()
    {
        if (game.level.bubbles.Count < game.level.maxBubbles)
        {
            game.level.bubbles.Add(this);
        }
        else
        {
            Destroy(gameObject);
            destroyed = true;
        }
    }

    private void OnDestroy()
    {
        game.level.bubbles.Remove(this);

        if (containable != null)
        {
            containable.transform.SetParent(null);
            containable.rb.isKinematic = false;
            containable.SetTrigger(false);

            foreach (var joint in FindObjectsOfType<FixedJoint>())
            {
                if (joint.connectedBody == rb)
                {
                    joint.connectedBody = containable.rb;
                }
            }
        }
    }

    private void OnTriggerEnter(Collider collider)
    {
        if (destroyed)
            return;

        var time = Time.time - startTime;
        if (time < stickAfter)
            return;

        if (containable != null)
            return;

        containable = collider?.attachedRigidbody?.GetComponent<Containable>();
        if (containable != null && collider.attachedRigidbody != null & !collider.attachedRigidbody.isKinematic)
        {
            transform.position = containable.transform.position;
            containable.rb.isKinematic = true;
            containable.rb.transform.SetParent(transform);
            containable.SetTrigger(true);
            body.excludeLayers = 0;

            foreach (var joint in FindObjectsOfType<FixedJoint>())
            {
                if (joint.connectedBody == containable.rb)
                {
                    joint.connectedBody = rb;
                }
            }
        }
    }
}