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

public class SpaceObject : MonoBehaviour
{
    public Vector3 velocity;
    public Vector2 startingVelocity;
    public MinimapIcon icon;
    public Collider2D aCollider2D;
    public bool hasRecentlyBeenEjected;
    public float ejectForce;
    public float rotationSpeed;

    protected virtual void Awake()
    {
        velocity = new Vector3(startingVelocity.x, startingVelocity.y);
        aCollider2D = GetComponent<Collider2D>();
        rotationSpeed = Random.Range(0.5f, 1f);
        if (Random.value < 0.5f)
        {
            rotationSpeed = -rotationSpeed;
        }
    }    

    private void Start()
    {
        GameManager.instance.spaceObjects.Add(this);
        GameObject iconObject = Instantiate(GameManager.instance.icon);
        iconObject.transform.parent = transform;
        iconObject.transform.localPosition = Vector3.zero;
        icon = iconObject.GetComponent<MinimapIcon>();
    }

    protected void FixedUpdate()
    {
        if (GameManager.instance.inventory.IsItemInInventory(this)) return;    
        if (this is Ship)
        {
            if (GetComponent<Ship>().isDead)
            {
                return;
            }
        }
        transform.position += velocity;
        GentlyRotate();
    }

    protected virtual void GentlyRotate()
    {
        transform.Rotate(new Vector3(0, 0, rotationSpeed));
    }

    public void RegisterAsEjected()
    {
        hasRecentlyBeenEjected = true;
        StartCoroutine(DelayUnregisteringAsEjected());
    }

    private IEnumerator DelayUnregisteringAsEjected()
    {
        yield return new WaitForSeconds(4);
        hasRecentlyBeenEjected = false;
    }
    
    public IEnumerator DestroyAfterDelay()
    {
        yield return new WaitForSeconds(3);
        GameManager.instance.spaceObjects.Remove(this);
        Destroy(gameObject);
    }
}
