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

public class Shatter : MonoBehaviour
{
    public static Shatter instance;
    public float shatterForce = 1f;
    private Rigidbody[] pieces;
    public AudioClip breakSound;
    private AudioSource audioSource;

    private void Start()
    {
        instance = this;
        List<Rigidbody> tempPieces = new List<Rigidbody>();

        for (int i = 0; i < transform.childCount; i++)
        {
            bool isPiece = transform.GetChild(i).name.Contains("Piece");
            if (isPiece)
                tempPieces.Add(transform.GetChild(i).GetComponent<Rigidbody>());
        }

        pieces = tempPieces.ToArray();

        for (int i = 0; i < pieces.Length; i++)
        {
            Rigidbody rbody = pieces[i];
            float rand1 = Random.Range(-1f, 1f);
            float rand2 = Random.Range(-1f, 1f);
            float rand3 = Random.Range(-1f, 1f);
            rbody.AddForce(new Vector3(rand1, rand2, rand3) * shatterForce);
        }
    }

    public void CountdownToShatter()
    {
        Invoke("SpawnNewShatter", 3f);
        VasePiece.placedPieces.Clear();
    }

    public void SpawnNewShatter()
    {
        VasePiece.placedPieces.Clear();

        VasePiece[] pieces = FindObjectsOfType<VasePiece>();

        for (int i = 0; i < pieces.Length; i++)
        {
            pieces[i].enabled = true;
            pieces[i].GetComponent<Rigidbody>().useGravity = true;
            pieces[i].GetComponent<Rigidbody>().isKinematic = false;
        }

        audioSource = GetComponent<AudioSource>();
        audioSource.PlayOneShot(breakSound, 0.7F);
    }
}