﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Linq;

namespace Arugula.Prototypical
{
    public class Pickup : MonoBehaviour
    {

        public static List<Pickup> All = new List<Pickup>();
        public static Pickup[] GetWithin(Vector3 pos, float dist)
        {
            return All.Where(x => !x.Used && Vector3.Distance(x.transform.position, pos) < dist).ToArray();
        }

        public static Pickup[] GetWithin(Pickup[] subset, Vector3 pos, float dist)
        {
            return subset.Where(x => !x.Used && Vector3.Distance(x.transform.position, pos) < dist).ToArray();
        }

        public event System.Action<Pickup> OnUsed = delegate { };
        public bool Used { get; private set; }
        public object User { get; private set; }
        public Rigidbody rb;
        public bool autoDestroy = true;

        private void OnEnable()
        {
            rb = GetComponent<Rigidbody>();
            All.Add(this);
        }

        private void OnDisable()
        {
            All.Remove(this);
        }

        public void Use(object user = null)
        {
            Used = true;
            User = user;
            OnUsed(this);
            if (autoDestroy)
                Destroy(gameObject);
        }
    }
}
