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

public class PickingUp : MonoBehaviour {

    public Transform sprite;
    public List<Transform> heldItems = new List<Transform>();

    private void OnTriggerStay(Collider other) {

        if (Input.GetKeyDown(KeyCode.Space)) {
            if (other.CompareTag("Item") && heldItems.Count < 2) {
                heldItems.Add(other.transform);
                other.transform.parent = sprite;
                other.GetComponent<Rigidbody>().velocity = Vector3.zero;
                other.GetComponent<Rigidbody>().isKinematic = true;
                other.GetComponent<Collider>().enabled = false;
                transform.parent.GetComponent<AudioSource>().PlayOneShot(transform.parent.GetComponent<Sounds>().sounds[0]);

            }
        }   
    }

    private void Update() {
        if (heldItems.Count > 0) {
            for (int i = 0; i < heldItems.Count; i++) {
                Transform t = heldItems[i];
                t.localPosition = new Vector3(0, 3+((i + 1)*2), -0.5f);
            }
        }

        if (Input.GetKeyDown(KeyCode.LeftShift) && heldItems.Count > 0) {
            Transform lastItem = heldItems[heldItems.Count - 1];
            lastItem.parent = null;
            lastItem.GetComponent<Rigidbody>().isKinematic = false;
            lastItem.GetComponent<Collider>().enabled = true;
            heldItems.Remove(lastItem);
            float angle = Random.Range(30, 180 - 30);
            Vector3 force = new Vector3(Mathf.Cos(angle) * 2, Mathf.Sin(angle) * 2, 0);
            lastItem.GetComponent<Rigidbody>().AddForce(force, ForceMode.Impulse);
        }
    }
}
