using System;
using System.Drawing;
using FastReport.Utils;
using FastReport.DevComponents.DotNetBar;
using System.Windows.Forms;

namespace FastReport.Controls
{
    internal class ColorButtonItem : ButtonItem
    {
        protected ControlContainerItem host;
        private ColorSelector colorSelector;
        private Color defaultColor;
        private bool lockImageChanged;

        public Color Color
        {
            get { return colorSelector.Color; }
            set { colorSelector.Color = value; }
        }

        public Color DefaultColor
        {
            get { return defaultColor; }
            set
            {
                defaultColor = value;
                UpdateImage(false);
            }
        }

        public override void OnImageChanged()
        {
            base.OnImageChanged();
            if (lockImageChanged)
                return;
            lockImageChanged = true;
            UpdateImage(true);
            lockImageChanged = false;
        }

        public void SetStyle(UIStyle style)
        {
            colorSelector.SetStyle(style);
        }

        private void UpdateImage(bool clone)
        {
            if (Image != null)
            {
                Image bitmap = clone ? Image.Clone() as Image : Image;
                using (Graphics g = Graphics.FromImage(bitmap))
                {
                    Color color = DefaultColor == Color.Transparent ? Color.White : DefaultColor;
                    using (Brush b = new SolidBrush(color))
                    {
                        float m = bitmap.Width / 16f;
                        g.FillRectangle(b, new RectangleF(1, 13 * m, 15 * m, 3 * m));
                    }
                }
                Image = bitmap;
            }
        }

        private void ColorButtonItem_PopupOpen(object sender, EventArgs e)
        {
            colorSelector.UpdateDpiDependencies(ContainerControl as Control);
        }

        private void FColorSelector_ColorSelected(object sender, EventArgs e)
        {
            Color = colorSelector.Color;
            DefaultColor = Color;
            ClosePopup();
            RaiseClick();
        }

        public ColorButtonItem()
        {
            PopupType = ePopupType.ToolBar;
            colorSelector = new ColorSelector();
            colorSelector.ColorSelected += new EventHandler(FColorSelector_ColorSelected);
            host = new ControlContainerItem();
            host.Control = colorSelector;
            SubItems.Add(host);
            this.PopupOpen += ColorButtonItem_PopupOpen;
        }

        public ColorButtonItem(int imageIndex, Color defaultColor) : this()
        {
            ImageIndex = imageIndex;
            DefaultColor = defaultColor;
        }

    }
}
