using System.Drawing;
using System.Reflection;
using Telerik.WinControls;
using Telerik.WinControls.UI;

namespace Pilz.Plugins.Advanced
{
    public static class Extensions
    {
        public static Icon? ToIcon(this Image image)
        {
            if (image is Bitmap bitmap)
                return Icon.FromHandle(bitmap.GetHicon());
            return null;
        }

        public static RadMenuItem GetAsItem(this PluginModule module)
        {
            return GetAsItem(module, true);
        }

        public static RadMenuItem GetAsItem(this PluginModule module, bool addDefaultHandler)
        {
            return GetAsItem(module, addDefaultHandler ? RadMenuItem_RMMethod_Click : null);
        }

        public static RadMenuItem GetAsItem(this PluginFunction function)
        {
            return GetAsItem(function, true);
        }

        public static RadMenuItem GetAsItem(this PluginFunction function, bool addDefaultHandler)
        {
            return GetAsItem(function, addDefaultHandler ? RadMenuItem_RMFunction_Click : null);
        }

        public static RadMenuItem GetAsItem(this PluginFeature module, EventHandler? clickHandler)
        {
            var item = new RadMenuItem
            {
                Text = module.Name,
                SvgImage = module.Icon,
                Tag = module,
                Visibility = module.Enabled ? ElementVisibility.Visible : ElementVisibility.Collapsed
            };

            if (clickHandler is not null)
                item.Click += clickHandler;

            return item;
        }

        private static void RadMenuItem_RMMethod_Click(object? sender, EventArgs e)
        {
            if (sender is RadMenuItem item && item.Tag is PluginModule function)
                function.ShowUI();
        }

        private static void RadMenuItem_RMFunction_Click(object? sender, EventArgs e)
        {
            if (sender is RadMenuItem item && item.Tag is PluginFunction function)
                function.Execute();
        }
    }
}