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

public class ChangingBox : MonoBehaviour {

    public List<Mesh> Meshes;

    private MeshRenderer Rend;
    private MeshFilter Filter;
    private MeshCollider Coll;

    private bool IsVisibleByCamera = false;
    private Bounds MeshBounds;

    // Use this for initialization
    void Start () {
        Rend = GetComponent<MeshRenderer>();
        Filter = GetComponent<MeshFilter>();
        Coll = GetComponent<MeshCollider>();

        MeshBounds = Rend.bounds;
    }
	
	// Update is called once per frame
	void Update () {
        bool CurrentVisible = GeometryUtility.TestPlanesAABB(GeometryUtility.CalculateFrustumPlanes(GameManager.Instance.Cam), MeshBounds);
        if (!CurrentVisible && IsVisibleByCamera)
        {
            SwitchObject();
        }
        IsVisibleByCamera = CurrentVisible;
    }

    void SwitchObject()
    {
        Vector3 PlayerToObject = GameManager.Instance.GetPlayerPosition() - transform.position;
        if (PlayerToObject.magnitude>4.0f)
        {
            Mesh NewMesh = Meshes[Random.Range(0, Meshes.Count)];
            Filter.sharedMesh = NewMesh;
            Coll.sharedMesh = NewMesh;
            //Rend.enabled = (Random.Range(0.0f,1.0f)>0.2f);

            Quaternion NewRot = new Quaternion();
            NewRot.eulerAngles = new Vector3(0.0f, Random.Range(0, 4) * 90.0f, 0.0f);
            transform.rotation = NewRot;
        }
    }
}
