using System.Collections.Generic;
using System.Windows.Forms;

namespace Pilz.UI.Utils;


public static class DrawingControl
{

    private const int WM_SETREDRAW = 11;
    private readonly static Dictionary<nint, int> dicSuspendCount = new Dictionary<nint, int>();

    public static void SuspendDrawing(this Control control)
    {
        if (!dicSuspendCount.ContainsKey(control.Handle))
            dicSuspendCount.Add(control.Handle, 1);
        else
        {
            dicSuspendCount[control.Handle] += 1;
        }

        if (dicSuspendCount[control.Handle] == 1)
            User32Bridge.SendMessage(control.Handle, WM_SETREDRAW, false, 0);
    }

    public static void ResumeDrawing(this Control control)
    {
        control.ResumeDrawing(true);
    }

    public static void ResumeDrawing(this Control control, bool redraw)
    {
        bool doRedraw = true;

        if (dicSuspendCount.ContainsKey(control.Handle))
        {
            dicSuspendCount[control.Handle] -= 1;
            if (dicSuspendCount[control.Handle] >= 1)
                doRedraw = false;
        }

        if (doRedraw)
        {
            User32Bridge.SendMessage(control.Handle, WM_SETREDRAW, true, 0);
            if (redraw)
                control.Refresh();
        }
    }

}