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

public class ScrapManager : MonoBehaviour
{
    //Audio
    [SerializeField] private AudioSource m_audioSource = null;
    [SerializeField] private List<AudioClip> m_audios = new List<AudioClip>();

    //Scrap Spawning
    [SerializeField] private int m_minScrap = 2;
    [SerializeField] private int m_maxScrap = 5;
    [SerializeField] private GameObject m_scrapRock = null;

    //Scrap Storage
    private List<GameObject> m_scraps = new List<GameObject>();

    private void Start()
    {
        MapManager.OnTileChanged += TileBroke;
    }

    private void TileBroke(TileChange change)
    {
        playAudio(change.NewTile);

        if (change.OldTile == Tile.TileType.Wall)
        {
            Debug.Log("Success");
            for (int i = 0; i < ScrapAmount(); i++)
            {
                m_scraps.Add(Instantiate(m_scrapRock, SpawnLocation(change.NewTile), Quaternion.Euler(RandomRotation()), transform));
            }
        }
        else
        {
            Debug.Log("Fail");
        }
    }

    //Helpers
    private int ScrapAmount()
    {
        return Random.Range(m_minScrap, m_maxScrap + 1);
    }

    private void playAudio(Tile t)
    {
        m_audioSource.transform.position = MapManager.TileToWorld(t);
        m_audioSource.PlayOneShot(m_audios[Random.Range(0, m_audios.Count)]);
    }

    private Vector3 SpawnLocation(Tile t)
    {
        Vector3 position = MapManager.TileToWorld(t);
        position.x += Random.Range(-0.5f, 0.5f);
        position.z += Random.Range(-0.5f, 0.5f);
        position.y += 0.25f;

        return position;
    }

    private Vector3 RandomRotation()
    {
        return new Vector3(Random.Range(0, 360 + 1), Random.Range(0, 360 + 1), Random.Range(0, 360 + 1));
    }
}
