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

public class ItemBoxScript :  MonoBehaviourPunCallbacks {

	[HideInInspector]
	public Transform innerIcon;

    [Header("Debug")]
    [SerializeField] DebugChannelSO m_debugChannel;

    // 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);
    }

	void OnTriggerEnter (Collider col)
    {
        // If we hit a player...
		if (col.tag == "Player")
        {
            // Get the racer core
			RacerCore racer = col.GetComponent<RacerCore> ();

            // If we didn't one, return
            if (!racer)
                return;

            // If this is not a local player, return
            if (!racer.IsLocal)
                return;

            if (m_debugChannel)
                m_debugChannel.Raise(this, "Item Box # " + photonView.ViewID + " has hit the local player!");

            racer.Items.RollItem();

			GetComponent<MeshRenderer> ().enabled = false;
			GetComponent<Collider> ().enabled = false;

			if (photonView && PhotonNetwork.IsConnected)
				photonView.RPC ("ActivateItemBox", RpcTarget.Others);
			
			StartCoroutine(BoxReset());
		}
	}

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

        if (m_debugChannel)
            m_debugChannel.Raise(this, "Item Box #" + photonView.ViewID + " has reset!");
	}

	[PunRPC]	
	public void ActivateItemBox () {
        if (m_debugChannel)
            m_debugChannel.Raise(this, "Item Box #" + photonView.ViewID + " has hit a networked player!");

        GetComponent<MeshRenderer> ().enabled = false;
		GetComponent<Collider> ().enabled = false;
		StartCoroutine (BoxReset ());
	}
}
