using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class BlackHole : MonoBehaviour
{
    public Collider2D aCollider2D;

    private void Awake()
    {
        aCollider2D = GetComponent<Collider2D>();
    }

    private void LateUpdate()
    {
        foreach(SpaceObject spaceObject in GameManager.instance.spaceObjects)
        {
            if (GameManager.instance.inventory.IsItemInInventory(spaceObject)) continue;

            Vector3 difference = this.transform.position - spaceObject.transform.position;
            Vector3 direction = difference.normalized;
            float distance = difference.magnitude;
            float distanceSquared = distance * distance;

            spaceObject.velocity +=
                  direction / distanceSquared 
                * GameManager.instance.blackHoleGravity 
                * GameManager.instance.gravityMultipler;
        }

        CheckCollisions();
    }

    private void CheckCollisions()
    {
        foreach (SpaceObject spaceObject in GameManager.instance.spaceObjects)
        {
            if (aCollider2D.IsTouching(spaceObject.aCollider2D))
            {
                if (spaceObject is Ship)
                {
                    Ship ship = spaceObject.GetComponent<Ship>();
                    ship.BlackHoleDeath();
                }
                else
                {
                    spaceObject.transform.position = new Vector3(-999999, 0, 0);
                    spaceObject.velocity = Vector3.zero;
                }
            }
        }
    }

}
