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

public class objectInteract : MonoBehaviour {

    public float force =1000;
    public int playerNumber = 1;
    public float carryDistance = 3f;
    private Camera cami;
    private bool attached = false;
    private RaycastHit hit;
    GameObject grabbeditem;

    void Start()
    {
        cami = GetComponentInChildren<Camera>();
    }
	
	// Update is called once per frame
	void Update ()
    {

       
        GetComponent<Camera>();
       // Debug.DrawRay(cami.transform.position, cami.transform.forward , Color.blue, 50);

        if (Input.GetButtonDown("GrabItem" + playerNumber))
        {
           // print("nappi toimii");
            if (attached)
            {
                grabbeditem.GetComponent<Rigidbody>().velocity = Vector3.zero;
                grabbeditem.transform.parent = null;
                attached = false;
                grabbeditem.GetComponent<Rigidbody>().isKinematic = false;
                grabbeditem = null;
                
            }
            else
            {
                //laitappa kameraan jne. 
                if (Physics.Raycast(cami.transform.position, cami.transform.forward, out hit, 5))
                {
         //           print("The Raycast is working");
                    if (hit.collider.gameObject.CompareTag("Item"))
                    {
             //           print("Raycast hit box");
                        attached = true;
                        grabbeditem = hit.collider.gameObject;
                        grabbeditem.GetComponent<Rigidbody>().isKinematic = true;
                    }

                }
                
            }
        }
        if (attached)
        {
            grabbeditem.transform.rotation = Quaternion.Euler(0, 0, 0);
            grabbeditem.transform.parent = cami.transform;
            grabbeditem.transform.position = cami.transform.position +cami.transform.forward*carryDistance;
        }

	}
    private void FixedUpdate()
    {
        if (attached && Input.GetButtonDown("Throw" +playerNumber))
        {
            grabbeditem.GetComponent<Rigidbody>().isKinematic = false;
            grabbeditem.GetComponent<Rigidbody>().AddForce(cami.transform.forward * force);
            grabbeditem.transform.parent = null;
            
            attached = false;

        }

    }
}
