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

public class PlanetEncounterController : MonoBehaviour
{
    // Start is called before the first frame update
    void Start()
    {
    }

    // Update is called once per frame
    void Update()
    {
        SpriteRenderer sr = this.GetComponent<SpriteRenderer>();
        sr.color = HasShipCollision ? Color.red : Color.white;
    }

    private List<ShipController> ShipCollisions = new List<ShipController>();

    public bool HasShipCollision
    {
        get { return ShipCollisions.Count > 0; }
    }

    private void OnTriggerEnter2D(Collider2D collision)
    {
        ShipController c = collision.gameObject.GetComponent<ShipController>();
        TargetPlanet tp = this.GetComponent<TargetPlanet>();
        if (c && !ShipCollisions.Contains(c))
        {
            ShipCollisions.Add(c);
            Crew[] allTheCrew = c.gameObject.GetComponentsInChildren<Crew>();
            foreach (Crew crew in allTheCrew)
            {
              if (tp.RequiredCrew.Contains(crew.CType))
              {
                crew.TransferTo(this.gameObject);
                tp.RequiredCrew.Remove(crew.CType);
              }
            }
        }
        
        // TODO: If ship is empty, load same player crew onboard.
        // TODO: If ship is not empty, unload crew to planet.
        
        
    }

    private void OnTriggerExit2D(Collider2D collision)
    {
        ShipController c = collision.gameObject.GetComponent<ShipController>();
        if (c && ShipCollisions.Contains(c))
        {
            ShipCollisions.Remove(c);
        }
    }
}
