import linuxcnc

def get_handlers(halcomp,builder,useropts):
    return [HandlerClass(halcomp,builder,useropts)]

class HandlerClass:
    def __init__(self, halcomp,builder,useropts):
        self.halcomp = halcomp
        self.builder = builder
        self.cmd = linuxcnc.command()
        self.stat = linuxcnc.stat()

    # check if linuxcnc is not running code
    def running(self, s, do_poll=True):
        if do_poll: s.poll()
        return s.task_mode == linuxcnc.MODE_AUTO and s.interp_state != linuxcnc.INTERP_IDLE

    # ensure linuxcnc is in the requested mode
    def ensure_mode(self, s, c, *modes):
        s.poll()
        if not modes: return False
        if s.task_mode in modes: return True
        if self.running(s, do_poll=False): return False
        c.mode(modes[0])
        c.wait_complete()
        return True

    # run an MDI command on button press
    def on_button_probe_z_clicked(self, widget, data=None):
        print ('MDI button Pressed')
        if self.ensure_mode(self.stat, self.cmd, linuxcnc.MODE_MDI):
            self.cmd.mdi('(MSG, MDI Worked!)')

  
