using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using AGXUnity;
using AGXUnity.Utils;

/// <summary>
/// This class is responsible for removing any Shape (and parent RigidBody) when it get into contact
/// with the Shape component
/// </summary>
public class CanRemover : ScriptComponent
{
  private agxCollide.Geometry m_sensorGeometry;

  // Start is called before the first frame update
  protected override void OnEnable()
  {
    // Get the shape that is attached as a Component together with this script
    var sensor = GetComponent<AGXUnity.Collide.Shape>();

    // Register a callback when anything collides with this sensor shape
    AGXUnity.Simulation.Instance.ContactCallbacks.OnContact(RemoveCan, sensor);

    m_sensorGeometry = sensor.NativeGeometry;
  }

  /// <summary>
  /// This method will be called upon contact between the "Remove" sensor and any other Shape
  /// </summary>
  /// <param name="contactData"></param>
  /// <returns></returns>
  private bool RemoveCan(ref AGXUnity.ContactData contactData)
  {
    var component = contactData.Component1;

    // We do not want to remove the sensor, so the other shape is the one we want
    if (m_sensorGeometry == contactData.Geometry1)
    {
      component = contactData.Component2;
    }


    // This is a somewhat special case:
    // We now know the ScriptComponent of the Shape we want to remove: component
    // But what we really want to remove is the whole bottle, including the RigidBody and the visual representation
    // That is the parent of this component.
    // This is however specific to this SodaCan prefab. For a different, more complex structure it might not be correct.
    // But here we know that the parent of the Cylinder shape IS the gameObject we want to remove.
    var prefab = component.gameObject.transform.parent.gameObject;

    // Sanity check so that we only remove objects that contain the string "Can"
    if (!prefab.name.Contains("Can"))
      return false;

    //Debug.Log("Removing: " + prefab.name);

    if (prefab)
    {
      Destroy(prefab);
      return false;
    }

    return false;
  }
}
