using Silk.NET.Maths;

namespace Microsoft.Iris.Render.OpenGL
{
    /// <summary>
    /// A leaf visual that paints a textured/colored quad. Content comes from its
    /// <see cref="IEffect"/> (typically an image effect); absent an image it fills
    /// with the sprite's debug color, which keeps placeholder content visible.
    /// </summary>
    public sealed class GLSprite : GLVisual, ISprite
    {
        private int m_nineGridLeft, m_nineGridTop, m_nineGridRight, m_nineGridBottom;

        public GLSprite(GLRenderSession session, object ownerData)
            : base(session, ownerData)
        {
        }

        public IEffect? Effect { get; set; }
        public bool RelativeSize { get; set; }

        public void SetCoordMap(int idxLayer, CoordMap coordMap)
        {
            // TODO(stage 3): honor per-layer coordinate remaps. Not required for the
            // basic textured-quad path; stored intent is dropped for now.
        }

        public void SetNineGrid(int left, int top, int right, int bottom)
        {
            m_nineGridLeft = left;
            m_nineGridTop = top;
            m_nineGridRight = right;
            m_nineGridBottom = bottom;
            // TODO(stage 3): implement 9-slice stretching. Currently the sprite is
            // drawn as a single stretched quad regardless of these insets.
        }

        internal override void Render(SceneRenderer renderer, Matrix4X4<float> parentMatrix, float inheritedAlpha)
        {
            if (!Visible || Size.X <= 0f || Size.Y <= 0f)
                return;

            Matrix4X4<float> matrix = LocalMatrix * parentMatrix;
            float alpha = inheritedAlpha * Alpha;

            GLImage? image = (Effect as GLEffect)?.PrimaryImage;
            if (image != null)
            {
                renderer.DrawTexturedQuad(matrix, Size.X, Size.Y, image, alpha);
            }
            else
            {
                ColorF c = DebugColor;
                // A zeroed ColorF would be fully transparent black; only draw when the
                // caller actually assigned a debug color.
                if (c.A > 0f)
                    renderer.DrawColoredQuad(matrix, Size.X, Size.Y, c, alpha);
            }
        }
    }
}
