using System;
using System.Data;
using System.Configuration;
using System.Drawing.Text;
using System.Drawing;
using System.Collections.Generic;
using Flipmind.Drawing;

namespace ImageTemplateNet
{
    /// <summary>
    /// Draws Text onto the generated image
    /// </summary>
    public class TextTemplateElement : TemplateElement
    {
        /// <summary>
        /// 
        /// </summary>
        /// <param name="context"></param>
        public override void Draw(DrawContext context)
        {
            TextElementConfig textConfig = (TextElementConfig)context.ElementConfig;
            Graphics g = context.Graphics;
            Font font = textConfig.Font;
            StringFormat stringFormat = textConfig.GetStringFormat();
            Brush b = new SolidBrush(textConfig.ForeColor);
            g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
            g.TextRenderingHint = TextRenderingHint.AntiAlias;
            RectangleF drawBounds;

            if (textConfig.WidthSetting.IsEmpty || textConfig.HeightSetting.IsEmpty)
            {
                SizeF size = GetStringSize(g, textConfig); // Only work out string size if we need to
                drawBounds = new RectangleF(textConfig.X, textConfig.Y, size.Width, size.Height);
            }
            else
            {
                drawBounds = textConfig.FBounds;
            }

            if (textConfig.AutoFit) // Resize the font until it fits
            {
                font = FontUtility.GetClosestFit(g, font, textConfig.Text, drawBounds.Size, textConfig.MinimumFontSize);
            }
            g.DrawString(textConfig.Text, font, b, drawBounds, stringFormat);
        }
        
        /// <summary>
        /// 
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public override Rectangle GetBounds(DrawContext context)
        {
            TextElementConfig textConfig = (TextElementConfig)context.ElementConfig;
            Graphics g = context.Graphics;
            SizeF size = GetStringSize(g, textConfig);
            return new Rectangle(textConfig.X, textConfig.Y, (int)size.Width, (int)size.Height);
        }

        #region "Private Methods"

        private SizeF GetStringSize(Graphics g, TextElementConfig textConfig) 
        {
            Font font = textConfig.Font;
            SizeF size;
            if (!textConfig.WidthSetting.IsEmpty)
            {
                size = g.MeasureString(textConfig.Text, font, textConfig.Size.Width);
            }
            else
            {
                size = g.MeasureString(textConfig.Text, font);
            }            
            return size;
        }
        #endregion

    }

}