using UnityEngine;
using UnityEngine.Tilemaps;

public class CannonManager : MonoBehaviour
{
    public Tilemap[] tilemaps;
    public GameObject bulletPrefab;
    public float fireRate = 2f;
    public TileBase cannonTile;

    private float timer;

    void Update()
    {
        timer += Time.deltaTime;

        if (timer >= fireRate)
        {
            FireAllCannons();
            timer = 0;
        }
    }

    void FireAllCannons()
    {
        foreach (Tilemap t in tilemaps)
        {
            if (t == null) continue;

            BoundsInt bounds = t.cellBounds;

            foreach (var pos in bounds.allPositionsWithin)
            {
                TileBase tile = t.GetTile(pos);
                if (tile == cannonTile)
                {
                    Vector3 worldPos = t.GetCellCenterWorld(pos);

                    // Unity 6 Tilemap Rotation check
                    Matrix4x4 matrix = t.GetTransformMatrix(pos);
                    Quaternion rotation = matrix.rotation;

                    GameObject new_bullet = Instantiate(bulletPrefab, worldPos, rotation);
                    new_bullet.GetComponent<SpriteRenderer>().sortingOrder = t.GetComponent<TilemapRenderer>().sortingOrder;

                    SoundManager.Instance.PlaySound("cannon", 0.7f);
                }
            }
        }
    }
}