using System.Drawing.Drawing2D;
using System.Runtime.InteropServices;

namespace Zcbot.WindowsNode;

internal static class TrayIconFactory
{
    internal static Icon Create(NodeState state)
    {
        var color = state switch
        {
            NodeState.Online => Color.FromArgb(34, 197, 94),
            NodeState.Connecting => Color.FromArgb(245, 158, 11),
            NodeState.NotRegistered or NodeState.AuthenticationRequired => Color.FromArgb(239, 68, 68),
            _ => Color.FromArgb(107, 114, 128),
        };
        using var bitmap = new Bitmap(32, 32);
        using var graphics = Graphics.FromImage(bitmap);
        graphics.SmoothingMode = SmoothingMode.AntiAlias;
        graphics.Clear(Color.Transparent);
        using var background = new SolidBrush(Color.FromArgb(30, 41, 59));
        using var badge = new SolidBrush(color);
        using var textBrush = new SolidBrush(Color.White);
        graphics.FillEllipse(background, 1, 1, 30, 30);
        using var font = new Font("Segoe UI", 13, FontStyle.Bold, GraphicsUnit.Pixel);
        graphics.DrawString("Z", font, textBrush, new PointF(8, 7));
        graphics.FillEllipse(badge, 20, 20, 11, 11);
        using var border = new Pen(Color.White, 2);
        graphics.DrawEllipse(border, 20, 20, 11, 11);

        var handle = bitmap.GetHicon();
        try
        {
            using var icon = Icon.FromHandle(handle);
            return (Icon)icon.Clone();
        }
        finally
        {
            DestroyIcon(handle);
        }
    }

    [DllImport("user32.dll")]
    [return: MarshalAs(UnmanagedType.Bool)]
    private static extern bool DestroyIcon(nint handle);
}
