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

[RequireComponent(typeof(Rigidbody))]
public class Item : MonoBehaviour {
    [Header("Runtime values")]
    public bool Grabbed = false;

    private Rigidbody Body;
    private Transform World;
    private bool BeingPlaced = false;
    private Vector3 TargetPosition;
    private Vector3 GrabOffset;

    private void Awake() {
        Body = GetComponent<Rigidbody>();
        World = GameObject.FindGameObjectWithTag("World").transform;
    }

    private void Update() {
        if (Grabbed) {
            transform.localPosition = Vector3.Lerp(transform.localPosition, GrabOffset, 10f * Time.deltaTime);
        } else if (BeingPlaced) {
            // Lerp to TargetPosition, then continue simulation
            Vector3 Delta = TargetPosition - transform.position;
            float Diff = Delta.magnitude;
            if (Diff < 0.1f) {
                transform.position = TargetPosition;
                Body.isKinematic = false;
                BeingPlaced = false;
            } else {
                transform.position = Vector3.Lerp(transform.position, TargetPosition, 20f * Time.deltaTime);
            }
        }
    }

    public void PickUp(Transform handTransform, Vector3 offset) {
        transform.parent = handTransform;
        GrabOffset = offset;
        Body.isKinematic = true;
        Grabbed = true;
    }

    public void Drop(Vector3 where) {
        transform.parent = World;
        TargetPosition = where;
        BeingPlaced = true;
        Grabbed = false;
    }
}
