using UnityEngine;

public class BarBase : MonoBehaviour
{
    public float firingSpeed = 0.03f;

    public bool canFireLeft = true;

    public bool canFireRight = true;

    public bool canFireTop = true;

    public bool canFireBottom = true;

    protected float firingTimer = 0.0f;

    protected Bounds bounds;

    protected bool canFire = true;

    protected void Initialize()
    {
        SpriteRenderer spriteRenderer = GetComponent<SpriteRenderer>();
        bounds = spriteRenderer.bounds;

        var walls = GameObject.FindGameObjectsWithTag("Wall");

        if (walls.Length > 0)
        {
            // Cap the firing ability if the bar is already intersecting with a wall.
            foreach (var wall in walls)
            {
                var wallBounds = wall.GetComponent<SpriteRenderer>().bounds;
                if (wallBounds.Intersects(bounds))
                {
                    canFire = false;

                    // Register the intersection with the WorldFiller.
                    var worldFiller = GameObject.FindAnyObjectByType<WorldFiller>();

                    if (worldFiller != null)
                    {
                        var intersectionBounds = GetIntersectionBounds(wallBounds, bounds);
                        worldFiller.SetWallPosition(intersectionBounds.center);
                    }

                    break;
                }
            }
        }
    }

    protected Bounds GetIntersectionBounds(Bounds wallBounds, Bounds barBounds)
    {
        Bounds intersectionBounds = new Bounds();

        intersectionBounds.SetMinMax(
            Vector3.Max(wallBounds.min, barBounds.min),
            Vector3.Min(wallBounds.max, barBounds.max)
        );

        return intersectionBounds;
    }
}
