using System;
using System.ComponentModel;
using System.Drawing;
using System.Linq;
using System.Windows.Forms;
using NotepadEnhanced.Helpers;

namespace NotepadEnhanced.GUI.Controls
{
    /// <summary>
    /// Represents a way of opening a ColorDialog and showing the currently picked color
    /// </summary>
    [DefaultEvent("ColorPicked")]
    public partial class ColorPickerControl : UserControl
    {
        [Description("Occurs when a new color is picked by the color picker dialog")]
        public event EventHandler ColorPicked;

        public ColorPickerControl()
        {
            InitializeComponent();
        }

        private void pnlBackColor_Click(object sender, EventArgs e)
        {
            using (var dlgColor = new ColorDialog())
            {
                dlgColor.Color = PickedColor;
                dlgColor.FullOpen = true;

                if (CustomColors != null && CustomColors.Length > 0)
                {
                    // Converts the custom colors to there int representations, so a color dialog can use them
                    dlgColor.CustomColors = CustomColors.Select(color => color.ToRgb()).ToArray();
                }

                if (dlgColor.ShowDialog() == DialogResult.OK)
                {
                    if (PickedColor != dlgColor.Color)
                    {
                        PickedColor = dlgColor.Color;

                        if (ColorPicked != null)
                            ColorPicked(this, EventArgs.Empty);
                    }
                }
            }
        }

        /// <summary>
        /// Gets or sets the color that is currently selected
        /// </summary>
        [Browsable(false)]
        public Color PickedColor
        {
            get { return pnlBackColor.BackColor; }
            set { pnlBackColor.BackColor = value; }
        }

        /// <summary>
        /// Gets or sets the custom colors that will be displayed for alternative picking
        /// </summary>
        [Browsable(false)]
        public Color[] CustomColors { get; set; }

        [Localizable(true)]
        [Description("The text to display on the control")]
        [Category("Appearance")]
        public string Caption
        {
            get { return lblCaption.Text; }
            set { lblCaption.Text = value; }
        }

        private void pnlBackColor_MouseEnter(object sender, EventArgs e)
        {
            this.Font = this.Font.SetStyle(FontStyle.Underline);
        }

        private void pnlBackColor_MouseLeave(object sender, EventArgs e)
        {
            this.Font = this.Font.SetStyle(FontStyle.Regular);
        }
    }
}
