using UnityEngine;
using UnityEngine.SceneManagement;

public class ExplosionTest : MonoBehaviour {

    // Public vars
    public GameObject target;
    public float explodeForce;
    public int shrapnelLayerIndex = 8;

    // Private vars
    bool exploded = false;

    void Update() {
        // Commence the polygonal chaos!
        if(Input.GetButtonDown("Jump") && !exploded) {
            exploded = true;
            Explode();

            // Destroy old object
            //Destroy(target);
        }
        // Restart test
        if(Input.GetButtonDown("Submit")) {
            SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex);
        }
    }

    void Explode() {
        Mesh originalMesh = target.gameObject.GetComponent<MeshFilter>().mesh; 
        Material originalMat = target.gameObject.GetComponent<Renderer>().material;
        int[] tris = originalMesh.triangles; // Get mesh's triangles. Array requires 3 indexes per triangle.
                                             // Parallel to vertex array.
                                        
        Vector3[] verts = originalMesh.vertices; // Get mesh's vertices;

        for(int t = 0; t < tris.Length; t += 3) { // Goes over every triangle
            GameObject newTri = new GameObject("Shrapnel");
            //Transform triTrans = newTri.AddComponent<Transform>();
            MeshFilter meshFilter = newTri.AddComponent<MeshFilter>();
            MeshRenderer meshRenderer = newTri.AddComponent<MeshRenderer>();
            Mesh newMesh = meshFilter.mesh;
            newMesh.Clear();

            Vector3[] tempVerts = new Vector3[3]; // Prepare to get new verts;

            // Get all three vertices for current triangle from triangle array
            for (int v = 0; v < 3; v++) { // Goes over individual vertices
                tempVerts[v] = verts[tris[v + t]];
            } 

            newMesh.vertices = tempVerts;
            newMesh.triangles = new int[] { 0, 1, 2};

            meshFilter.mesh = newMesh;
            meshRenderer.material = originalMat;

            Rigidbody rigidBody = newTri.AddComponent<Rigidbody>();
            //rigidBody.isKinematic = true;
            newTri.AddComponent<MeshCollider>();
            newTri.layer = shrapnelLayerIndex;

            Vector3 explodeDir = newTri.transform.position - target.transform.position;

            rigidBody.AddForce(explodeDir.normalized * explodeForce, ForceMode.Impulse);
        }
    }
	
}
