using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Photon.Pun;

public class ItemBoxScript : MonoBehaviourPunCallbacks {

	[HideInInspector]
	public Transform innerIcon;
	[HideInInspector]
	public RacerScript racer;
	[HideInInspector]
	public ItemCanvas canvas;

    // Start is called before the first frame update
    void Start() {
        
    }

    // Update is called once per frame
    void Update() {

		transform.RotateAround (transform.position, Vector3.up, 30f * Time.deltaTime);
		innerIcon.LookAt (2 * innerIcon.position - Camera.main.transform.position);
		if (!canvas) {
			canvas = GameObject.FindObjectOfType<ItemCanvas> ();
		}
    }

	void OnTriggerEnter (Collider col) {
		if (col.tag == "Player") {
			racer = col.transform.GetComponentInParent<RacerScript> ();
			GetComponent<MeshRenderer> ().enabled = false;
			GetComponent<Collider> ().enabled = false;
			if (photonView && PhotonNetwork.IsConnected) {
				photonView.RPC ("ActivateItemBox", RpcTarget.OthersBuffered);
			}
			canvas.ItemPickUp (racer);
			StartCoroutine (BoxReset ());
		}
	}

	IEnumerator BoxReset () {
		yield return new WaitForSeconds (10f);
		GetComponent<MeshRenderer> ().enabled = true;
		GetComponent<Collider> ().enabled = true;
		//racer = null;
	}

	[PunRPC]	
	public void ActivateItemBox () {
		GetComponent<MeshRenderer> ().enabled = false;
		GetComponent<Collider> ().enabled = false;
		StartCoroutine (BoxReset ());
	}
}
