using UnityEngine;
using System.Collections;

public class Grabber : MonoBehaviour
{
    //public PlayerController playerController;
    public Transform launchTransform;
    public Transform holdTransform;
    public Rigidbody heldRigidbody;
    public AudioClip pickupSound;

    public void LaunchHeld(Vector3 launchForce)
    {
        if(heldRigidbody != null)
        {
            heldRigidbody.isKinematic = false;
            heldRigidbody.transform.SetParent(null);
            heldRigidbody.gameObject.SetLayerRecursively(Layers.Projectile);
            heldRigidbody.transform.position = launchTransform.position;
            heldRigidbody.AddForce(launchForce, ForceMode.VelocityChange);
            heldRigidbody.AddTorque(Random.Range(-2f, 2f), Random.Range(-2f, 2f), Random.Range(-2f, 2f));
            heldRigidbody = null;
        }
    }

    void OnTriggerStay(Collider other)
    {
        Pickup(other.gameObject);
    }

    void OnTriggerEnter(Collider other)
    {
        Pickup(other.gameObject);
    }

    public void Pickup(GameObject gameObject)
    {
        if (gameObject.layer == Layers.Projectile || gameObject.layer == Layers.Stockpile)
        {
            if (heldRigidbody == null)
            {
                var rigidBody = gameObject.GetComponentInParent<Rigidbody>();
                if (rigidBody.velocity.sqrMagnitude.Approximately(0f))
                {
                    heldRigidbody = rigidBody;
                    heldRigidbody.transform.SetParent(holdTransform);
                    heldRigidbody.transform.localPosition = Vector3.zero;
                    heldRigidbody.isKinematic = true;
                    heldRigidbody.gameObject.SetLayerRecursively(Layers.Stockpile);
                    OneShot3DAudio.PlayClipAtPoint(pickupSound, transform.position);
                }
            }
        }
    }


}
