from annular_checker import annular_check
import pcbnew
import wx
import wx.aui
import threading
import time
import sys
import subprocess
import os
# import pcbnew
from pcbnew import *
# import base64
from wx.lib.embeddedimage import PyEmbeddedImage

plugin = annular_check()
plugin.register()


def check_for_annular_button():
    # From Miles McCoo's blog
    # https://kicad.mmccoo.com/2017/03/05/adding-your-own-command-buttons-to-the-pcbnew-gui/
    def find_pcbnew_window():
        windows = wx.GetTopLevelWindows()
        pcbnewwn = [w for w in windows if "Pcbnew" in w.GetTitle()]
        if len(pcbnewwn) != 1:
            return None
        return pcbnewwn[0]

    def callback(_):
        plugin.Run()

    import os
    path = os.path.dirname(__file__)
    bm = wx.Bitmap(path + '/annular.png', wx.BITMAP_TYPE_PNG)
    button_wx_item_id = 1
    while True:
        time.sleep(1.5)
        pcbwin = find_pcbnew_window()
        if not pcbwin:
            continue

        top_tb = pcbwin.FindWindowById(pcbnew.ID_H_TOOLBAR)
        if button_wx_item_id == 1 or not top_tb.FindTool(button_wx_item_id):
            #top_tb.AddSeparator()
            button_wx_item_id = wx.NewId()
            top_tb.AddTool(button_wx_item_id, "aChecker", bm,
                           "PCB Annular Checker", wx.ITEM_NORMAL)
                           
            top_tb.Bind(wx.EVT_TOOL, callback, id=button_wx_item_id)
            top_tb.Realize()


if 0:
    t = threading.Thread(target=check_for_annular_button)
    t.daemon = True
    t.start()
