from stdglue import *
import linuxcnc

# REMAP=M6 modalgroup=10 python=m6remap
#
# On a m67 tool change, probe the tool for length
# if the tool table length extry is zero.
# Otherwise, use the tool table length for the offset.
# 
# move to tool change position for toolchange
# wait for acknowledge of tool change
# If the tool table Z length for the current tool is greater than zero
#    move to tool setter probe position and probe tool on tool setter.
#    Use the length from the probe + value in #4001-#4008 as the offset.
# If the tool table Z length for the current tool is equal to zero
#    use the value from the tool table + value in #4001-#4008 as the offset.
# move back to tool change position
# set offsets
# based on Versaprobe remap
#
# required INI settings
# (Abs coordinates/ machine based units)
#
#[TOOLSENSOR]
#X = .0690
#Y = 6.631
#Z = -3.7
#SEARCH_VEL = 20
#PROBE_VEL = 5
#MAXPROBE = -5.95

def m6remap(self, **words):

    # only run this if we are really moving the machine
    # skip this if running task for the screen
    if not self.task:
        yield INTERP_OK

    IMPERIAL_BASED = not(bool(self.params['_metric_machine']))

    try:
        #Current coordinate system (ccs)
        ccs = int(self.params[5220])
        cJHKoffset = float(self.params[4001])

        print("--- Current Coordinate System = %d ---" % ccs)
        print("--- Current 4001 Offset = %f ---" % cJHKoffset)

        # we need to be in machine based units
        # if we aren't - switch
        # remember so we can switch back later
        switchUnitsFlag = False
        if bool(self.params["_imperial"]) != IMPERIAL_BASED:
            print ("not right Units: {}".format(bool(self.params["_imperial"])))
            if IMPERIAL_BASED:
                print ("switched Units to imperial")
                self.execute("G20")
            else:
                print ("switched Units to metric")
                self.execute("G21")
            switchUnitsFlag = True

        s = linuxcnc.stat()
        s.poll()
        original_position = s.actual_position
        print("X=%f" % original_position[0])
        print("Y=%f" % original_position[1])
        print("Z=%f" % original_position[2])
        print ("Current offset = %f" % s.g5x_offset[2])

        self.params["tool_in_spindle"] = self.current_tool
        self.params["selected_tool"] = self.selected_tool
        self.params["current_pocket"] = self.current_pocket
        self.params["selected_pocket"] = self.selected_pocket

        #print("Current tool: %d" % int(self.current_tool))
        #print("Selected tool: %d" % int(self.selected_tool))
        #print("Current pocket: %d" % int(self.current_pocket))
        #print("Selected pocket: %d" % int(self.selected_pocket))

        # cancel tool offset
        self.execute("G49")

        # change tool where ever we are
        # user sets toolchange position prior to toolchange
        # we will return here after

        try:
            self.selected_pocket =  int(self.params["selected_pocket"])
            emccanon.CHANGE_TOOL(self.selected_pocket)
            self.current_pocket = self.selected_pocket
            self.selected_pocket = -1
            self.selected_tool = -1
            # cause a sync()
            self.set_tool_parameters()
            self.toolchange_flag = True
        except InterpreterException as e:
            self.set_errormsg("m6remap remap error: %s" % (e))
            yield INTERP_ERROR

        yield INTERP_EXECUTE_FINISH

        #print("New Current tool: %d" % int(self.current_tool))
        #s = linuxcnc.stat()
        s.poll()

        if s.tool_table[0].id == 0: # Tool NOT loaded
            self.execute("G90")
            self.set_errormsg("m6remap Tool not loaded error:")
            yield INTERP_ERROR

        print(s.tool_table[0].zoffset)
        if s.tool_table[0].zoffset > 0:
            #Set offset using probed valued stored in 4001-4008 based on CCS
            print("Do NOT measure the tool")
            coffset = self.params[4000 + ccs]
            cmd = "G10 L2 P%d Z%f" % (ccs,coffset)
            print (cmd)
            self.execute(cmd)

            if switchUnitsFlag:
                if IMPERIAL_BASED:
                    self.execute("G21")
                    print ("switched Units back to metric")
                else:
                    self.execute("G20")
                    print ("switched Units back to imperial")
            self.execute("G90")
            return None

        print("Measure the tool")
        try:
            # move to tool probe position (from INI)
            self.execute("G90")
            self.execute("G53 G0 X[#<_ini[TOOLSENSOR]X>] Y[#<_ini[TOOLSENSOR]Y>]")
            print("move to probe start")
            self.execute("G53 G0 Z[#<_ini[TOOLSENSOR]Z_PROBE_START>]") #JHK Change

            # set incremental mode
            self.execute("G91")

            #Set coordinate system for my style of remap
            self.execute("G59.3")
            # course probe
            self.execute("F [#<_ini[TOOLSENSOR]SEARCH_VEL>]")
            self.execute("G38.2 Z [#<_ini[TOOLSENSOR]MAXPROBE>]")

            # Wait for results
            yield INTERP_EXECUTE_FINISH

            # FIXME if there is an error it never comes back
            # which leaves linuxcnc in g91 state
            if self.params[5070] == 0 or self.return_value > 0.0:
                self.execute("G90")
                self.set_errormsg("m6remap remap error:")
                yield INTERP_ERROR

            # rapid up off trigger point to do it again
            if bool(self.params["_imperial"]):
                f = 0.25
            else:
                f = 4.0
            self.execute("G43.1 Z0")  
            self.execute("G0 Z{}".format(f))
            self.execute("G59.3")
            self.execute("F [#<_ini[TOOLSENSOR]PROBE_VEL>]")
            self.execute("G38.2 Z-0.5")
            yield INTERP_EXECUTE_FINISH
            print("5063= %f" % float(self.params[5063]))

            # FIXME if there is an error it never comes back
            # which leaves linuxcnc in g91 state
            if self.params[5070] == 0 or self.return_value > 0.0:
                self.execute("G90")
                self.set_errormsg("m6remap remap error:")
                yield INTERP_ERROR

            # set back absolute state
            self.execute("G90")

            # return to recorded tool change position
            rtc_cmd = "G53 G0 Z%f" % original_position[2]
            print(rtc_cmd)
            self.execute(rtc_cmd)
            yield INTERP_EXECUTE_FINISH

            rtc_cmd = "G53 G0 X%f Y%f" % (original_position[0],original_position[1])
            print(rtc_cmd)
            self.execute(rtc_cmd)

            print("New calculation")
            workheight = self.params[4000 + ccs]
            print("workheight [4000 + ccs]= %f" % float(workheight))

            print("self.params[5063] = {}".format(self.params[5063]))
            proberesult = self.params[5063]
            print("proberesult= %f" % float(proberesult)) #JHK

            new_Z_offset = workheight + proberesult
            print("new_Z_offset = %f" % float(new_Z_offset)) #JHK

            #Set new offset for coordinate system.
            cmd = "G10 L2 P%d Z%f" % (ccs,new_Z_offset)
            print (cmd)
            self.execute(cmd)

            # apply tool offset
            self.execute("G43")

            #Restore coordinate system.
            if ccs == 1:
                self.execute("G54")
            if ccs == 2:
                self.execute("G55")
            if ccs == 3:
                self.execute("G56")
            if ccs == 4:
                self.execute("G57")
            if ccs == 5:
                self.execute("G58")
            if ccs == 6:
                self.execute("G59")
            if ccs == 7:
                self.execute("G59.1")
            if ccs == 8:
                self.execute("G59.2")
            #if ccs == 9 # This is used by the toolsetter
            #    self.execute("G59.3")

            print("--- Restored Coordinate System = %d ---" % ccs)

            # if we switched units for tool change - switch back
            if switchUnitsFlag:
                if IMPERIAL_BASED:
                    self.execute("G21")
                    print ("switched Units back to metric")
                else:
                    self.execute("G20")
                    print ("switched Units back to imperial")

        except InterpreterException as e:
            msg = "%d: '%s' - %s" % (e.line_number,e.line_text, e.error_message)
            print (msg)
            yield INTERP_ERROR

    except:
        self.set_errormsg("m6remap remap error." )
        yield INTERP_ERROR

    print("JHK End of remap")

