# Copyright 2015-2023 - RoboDK Inc. - https://robodk.com/
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

# ----------------------------------------------------
# This file is a sample POST PROCESSOR script to generate robodk programs for RoboDK
#
# To edit/test this POST PROCESSOR script file:
# Select "Program"->"Add/Edit Post Processor", then select your post or create a new one.
# You can edit this file using any text editor or Python editor. Using a Python editor allows to quickly evaluate a sample program at the end of this file.
# Python should be automatically installed with RoboDK
#
# You can also edit the POST PROCESSOR manually:
#    1- Open the *.py file with Python IDLE (right click -> Edit with IDLE)
#    2- Make the necessary changes
#    3- Run the file to open Python Shell: Run -> Run module (F5 by default)
#    4- The "test_post()" function is called automatically
# Alternatively, you can edit this file using a text editor and run it with Python
#
# To use a POST PROCESSOR file you must place the *.py file in "C:/RoboDK/Posts/"
# To select one POST PROCESSOR for your robot in RoboDK you must follow these steps:
#    1- Open the robot panel (double click a robot)
#    2- Select "Parameters"
#    3- Select "Unlock advanced options"
#    4- Select your post as the file name in the "Robot brand" box
#
# To delete an existing POST PROCESSOR script, simply delete this file (.py file)
#
# ----------------------------------------------------
# More information about RoboDK Post Processors and Offline Programming here:
#     https://robodk.com/help#PostProcessor
#     https://robodk.com/doc/en/PythonAPI/postprocessor.html
# ----------------------------------------------------
from robodk import robolink  # Robot toolbox

import os,math,sys

from robodk.robomath import eye, Mat, distance,pose_angle_between,Pose_2_TxyzRxyz
from robodk.robofileio import FilterName,DirExists
from robodk.robodialogs import getSaveFile, mbox


RDK_info = robolink.Robolink()
warning_run_post = False


HEADER_RDK = """# Type help("robodk.robolink") or help("robodk.robomath") for more information
# Press F5 to run the script
# Documentation: https://robodk.com/doc/en/RoboDK-API.html
# Reference:     https://robodk.com/doc/en/PythonAPI/robodk.html
# Note: It is not required to keep a copy of this file, your Python script is saved with your RDK project



from robodk import robolink

from robodk.robomath import Pose


"""

dict_runmode = {1:"robolink.RUNMODE_SIMULATE",
                2:"robolink.RUNMODE_QUICKVALIDATE",
                3:"robolink.RUNMODE_MAKE_ROBOTPROG",
                4:"robolink.RUNMODE_MAKE_ROBOTPROG_AND_UPLOAD",
                5:"robolink.RUNMODE_MAKE_ROBOTPROG_AND_START",
                6:"robolink.RUNMODE_RUN_ROBOT"
                }



def pose_2_str(pose, joints=None):
    """Prints a pose target"""
    if pose is None:
        pose = eye(4)
    x, y, z, rx, ry, rz = Pose_2_TxyzRxyz(pose)
    str_xyzwpr = 'Pose(%.3f, %.3f, %.3f,  %.3f, %.3f, %.3f)' % (x, y, z, rx * 180 / math.pi, ry * 180 / math.pi, rz * 180 / math.pi)
    return str_xyzwpr


def mat_2_str(mat):
    returnString = str(mat).split(":\n")[0].strip('(').strip(')').strip('Pose(')
    return returnString


def joints_2_str(joints):
    """Prints a joint target"""
    if joints is None:
        return ""

    str = ''
    for i in range(len(joints)):
        str = str + ('%.6f,' % (joints[i]))
    str = str[:-1]
    return str


# Parent: make sure the parent matches
def PoseDistance(pose1, pose2):
    """0.000001"""
    distance_mm = distance(pose1.Pos(), pose2.Pos())
    distance_deg = pose_angle_between(pose1, pose2) * 180 / pi
    return distance_mm + distance_deg


# ----------------------------------------------------
# Object class that handles the robot instructions/syntax
class RobotPost(object):
    """Robot post object"""

    

    #Name of the main function, obtained from first instance of ProgStart being called
    MAIN_PROGRAM_NAME = None


    PROG_PARAMS ={"remote_ip":""
                     }
    POP_UP = False
    #----------------------------------------------------


    #Unique Target Couter
    TARGET_COUNT = 0

    # other variables
    PROG_EXT = 'py'  # set the program extension
    ROBOT_POST = ''
    ROBOT_NAME = ''
    PROG_FILES = []

    PROG = []
    LOG = ''
    nAxes = 6
    REF_FRAME = eye(4)

    
    tab_extra = "\t"
    tab_count = 0

    RUN_MODE = robolink.RUNMODE_SIMULATE
    DISCONNECT_ENDPROG = False
    

    #Need to make the robot object here
    def __init__(self, robotpost=None, robotname=None, robot_axes=6, ip_com=r"""127.0.0.1""", **kwargs):
        self.ROBOT_POST = robotpost

        self.ROBOT_NAME = robotname
        self.PROG = []
        self.LOG = ''
        self.nAxes = robot_axes

        for k, v in kwargs.items():
            if k == 'lines_x_prog':
                self.MAX_LINES_X_PROG = v
            if k == 'remote_ip':
                self.PROG_PARAMS["remote_ip"]=v
        
        self.PROG_PARAMS["robot_name"] = self.ROBOT_NAME

        self.addline(HEADER_RDK.format_map(self.PROG_PARAMS))
  

    def ProgStart(self, progname):
        prognamesafe = FilterName(progname).replace('.', '')
        str_axes = ''
        for i in range(self.nAxes):
            str_axes += ',J%i (deg)' % (i + 1)
        if self.MAIN_PROGRAM_NAME is None:
            self.MAIN_PROGRAM_NAME = prognamesafe
        self.addline('')
        self.addline('# Program Start: ' + prognamesafe)
        self.addline('def ' + prognamesafe + '(RDK,robot):')

        self.tab_count+=1
        
        self.addline('# Generating program: ' + prognamesafe)
        self.addline('')

    def ProgFinish(self, progname):
        if self.DISCONNECT_ENDPROG and self.RUN_MODE >2 and self.RUN_MODE <6: 
            self.setRunMode(-1)
        self.addline('return')
        self.tab_count-=1
        

    def ProgSave(self, folder, progname, ask_user=False, show_result=False):
        

        if self.MAIN_PROGRAM_NAME is not None:
            self.addline('')
            self.addline('if __name__ == "__main__":\n')
            self.tab_count+=1
            self.addline("RDK = robolink.Robolink({remote_ip})".format_map(self.PROG_PARAMS))
            self.addline("")
            self.addline(f"RDK.setRunMode({dict_runmode[self.RUN_MODE]})")
            self.addline('robot = RDK.Item("{robot_name}",robolink.ITEM_TYPE_ROBOT)'.format_map(self.PROG_PARAMS))
           
            self.addline(self.MAIN_PROGRAM_NAME + '(RDK,robot)')

        progname = progname + '.' + self.PROG_EXT
        if ask_user or not DirExists(folder):
            filesave = getSaveFile(folder, progname, 'Save program as...')
            if filesave is not None:
                filesave = filesave.name
            else:
                return
        else:
            filesave = folder + '/' + progname
        fid = open(filesave, "w")
        for line in self.PROG:
            fid.write(line + '\n')
        fid.close()
        print('SAVED: %s\n' % filesave)
        self.PROG_FILES = filesave
        #---------------------- show result
        if show_result:
            if type(show_result) is str:
                # Open file with provided application
                import subprocess
                p = subprocess.Popen([show_result, filesave])
            elif type(show_result) is list:
                import subprocess
                p = subprocess.Popen(show_result + [filesave])
            else:
                # open file with default application
                import os
                os.startfile(filesave)

            if len(self.LOG) > 0:
                mbox('Program generation LOG:\n\n' + self.LOG)
        RDK = robolink.Robolink()
        RDK.AddFile(filesave)
        

    def ProgSendRobot(self, robot_ip, remote_path, ftp_user, ftp_pass):
        """Send a program to the robot using the provided parameters. This method is executed right after ProgSave if we selected the option "Send Program to Robot".
        The connection parameters must be provided in the robot connection menu of RoboDK"""
        RDK_info.ShowMessage("Sending Program to robot incompatible with this post processor")
        quit()
        #UploadFTP(self.PROG_FILES, robot_ip, remote_path, ftp_user, ftp_pass)
        import subprocess
        import sys

        print("POPUP: Running script file")
        sys.stdout.flush()

        #subprocess.call([sys.executable, filenameToOpen], shell = False)
        command = 'start "" "' + sys.executable + '" "' + self.PROG_FILES + '"'
        print("Running command: " + command)
        sys.stdout.flush()
        os.system(command)

    def MoveJ(self, pose, joints, conf_RLF=None):
        """Add a joint movement"""
        self.addline('robot.MoveJ([%s])' % (joints_2_str(joints)))

    def MoveL(self, pose, joints, conf_RLF=None):
        """Add a linear movement"""
        pose_abs = self.REF_FRAME * pose
        self.addline('robot.MoveL(%s)' % (pose_2_str(pose)))

    def MoveC(self, pose1, joints1, pose2, joints2, conf_RLF_1=None, conf_RLF_2=None):
        """Add a circular movement"""
        self.addline('robot.MoveC([%s])' % (joints_2_str(joints1) + ',' + mat_2_str(pose1) + ',' + joints_2_str(joints2) + ',' + mat_2_str(pose2)))

    def setFrame(self, pose, frame_id=None, frame_name=None):
        """Change the robot reference frame"""
        self.REF_FRAME = pose
        varname = FilterName(frame_name).replace('.', '')
        self.addline(f'robot.setPoseFrame({pose_2_str(pose)})')

    def setTool(self, pose, tool_id=None, tool_name=None):
        """Change the robot TCP"""
        self.addline('robot.setPoseTool(%s)' % ( pose_2_str(pose)))
        self.addline('')

    def Pause(self, time_ms):
        """Pause the robot program"""
        if time_ms < 0:
            self.addline('    print(\'STOP\')')
        else:
            self.addline('import time')
            self.addline('time.sleep(%.3f)' % (time_ms * 1000))

    def setSpeed(self, speed_mms):
        """Changes the robot speed (in mm/s)"""
        
        self.addline('robot.setSpeed(%s,-1,-1,-1)' %(str(speed_mms)))

    def setAcceleration(self, accel_mmss):
        """Changes the robot acceleration (in mm/s2)"""
        
        self.addline('robot.setSpeed(-1,-1,%s,-1)' %(str(accel_mmss)))

    def setSpeedJoints(self, speed_degs):
        """Changes the robot joint speed (in deg/s)"""
        
        self.addline('robot.setSpeed(-1,%s,-1,-1)' %( str(speed_degs)))

    def setAccelerationJoints(self, accel_degss):
        """Changes the robot joint acceleration (in deg/s2)"""
        
        self.addline('robot.setSpeed(-1,-1,-1,%s)' %( str(accel_degss)))

    def setZoneData(self, zone_mm):
        """Changes the rounding radius (aka CNT, APO or zone data) to make the movement smoother"""
        self.addline('robot.setRounding(%.3f)' %( zone_mm))

    def setDO(self, io_var, io_value):
        """Sets a variable (digital output) to a given value"""

        # at this point, io_var and io_value must be string values
        self.addline('robot.setDO(%s,%s)' %( io_var, io_value))

    def setAO(self, io_var, io_value):
        """Set an Analog Output"""
        self.setDO(io_var, io_value)

    def waitDI(self, io_var, io_value, timeout_ms=-1):
        """Waits for a variable (digital input) io_var to attain a given value io_value. Optionally, a timeout can be provided."""
        if timeout_ms > -1:
            timeout_ms = timeout_ms / 1000
        self.addline('robot.WaitDI(%s,%s,%s)' %( io_var, io_value, timeout_ms))
    def setRunMode(self,runmode):
        global warning_run_post
        if runmode == -1:
            self.addline("RDK.Finish()")
            return
        if runmode == 0:
            self.addline("RDK.NewLink()")
            return
        if runmode >2 and runmode <6:
            if not warning_run_post: 
                RDK_info.ShowMessage(f"Remember to change selected postprocessor before running output program")
            warning_run_post = True
        
            

        if self.RUN_MODE == runmode:
            return
        
        self.RUN_MODE=runmode
        self.addline(f"RDK.setRunMode({dict_runmode[runmode]})")

    def RunCode(self, code, is_function_call=False):
        """Adds code or a function call"""
        if is_function_call:
            prognamesafe = code.replace(' ', '_')
            #self.addline(code + '()')
            if self.RUN_MODE == -1:
                self.setRunMode(-1)#finish the current program before calling the new one
            
            elif code.startswith("MAKE_ROBOTPROG_AND_START"):
                self.setRunMode(5)
                return
            
            
            self.addline('%s = RDK.Item("%s",robolink.ITEM_TYPE_PROGRAM)' % (prognamesafe, code))
            self.addline('robot.RunInstruction("%s",robolink.INSTRUCTION_CALL_PROGRAM)' % (prognamesafe))

            if self.RUN_MODE == -1:
                self.setRunMode(0) #start a new link

        else:
            self.addline(code)

    def RunMessage(self, message, iscomment=False):
        """Display a message in the robot controller screen (teach pendant)"""
        if iscomment:
            self.addline(f'#{message}')
        else:
            self.addline(f'RDK.ShowMessage("{message}",{self.POP_UP})')

# ------------------ private ----------------------

    def addline(self, newline):
        """Add a program line"""
        tab = self.tab_extra*self.tab_count
        
        self.PROG.append(tab+newline)

    def addlog(self, newline):
        """Add a log message"""
        self.LOG = self.LOG + newline + '\n'


# -------------------------------------------------
# ------------ For testing purposes ---------------
def Pose(xyzrpw):
    [x, y, z, r, p, w] = xyzrpw
    a = r * math.pi / 180
    b = p * math.pi / 180
    c = w * math.pi / 180
    ca = math.cos(a)
    sa = math.sin(a)
    cb = math.cos(b)
    sb = math.sin(b)
    cc = math.cos(c)
    sc = math.sin(c)
    return Mat([[cb * ca, ca * sc * sb - cc * sa, sc * sa + cc * ca * sb, x], [cb * sa, cc * ca + sc * sb * sa, cc * sb * sa - ca * sc, y], [-sb, cb * sc, cc * cb, z], [0, 0, 0, 1]])


def test_post():
    """Test the post with a basic program"""

    def p(xyzrpw):
        x, y, z, r, p, w = xyzrpw
        a = r * math.pi / 180.0
        b = p * math.pi / 180.0
        c = w * math.pi / 180.0
        ca = math.cos(a)
        sa = math.sin(a)
        cb = math.cos(b)
        sb = math.sin(b)
        cc = math.cos(c)
        sc = math.sin(c)
        return Mat([[cb * ca, ca * sc * sb - cc * sa, sc * sa + cc * ca * sb, x], [cb * sa, cc * ca + sc * sb * sa, cc * sb * sa - ca * sc, y], [-sb, cb * sc, cc * cb, z], [0.0, 0.0, 0.0, 1.0]])

    robot = RobotPost(r"""Quine""", r"""uFactoryxArm""", 6, axes_type=['R', 'R', 'R', 'R', 'R', 'R'], ip_com=r"""192.168.125.1""")

    robot.ProgStart(r"""Prog1""")
    robot.RunMessage(r"""Program generated by RoboDK v4.2.3 for ABB IRB 120-3/0.6 on 08/05/2020 15:54:54""", True)
    robot.RunMessage(r"""Using nominal kinematics.""", True)
    robot.setFrame(p([0.000000, 0.000000, 0.000000, 0.000000, 0.000000, 0.000000]), -1, r"""ABB IRB 120-3/0.6 Base""")
    robot.setAccelerationJoints(800.000)
    robot.setFrame(p([0.000000, 0.000000, 0.000000, 0.000000, 0.000000, 0.000000]), -1, r"""ABB IRB 120-3/0.6 Base""")
    robot.setAccelerationJoints(800.000)
    robot.setSpeedJoints(500.000)
    robot.setAcceleration(3000.000)
    robot.setSpeed(500.000)
    robot.MoveJ(p([374.000000, -0.000000, 610.000000, -0.000000, 90.000000, 0.000000]), [-0.000000, -0.836761, 4.599793, -0.000000, -3.763032, 0.000000], [0.0, 0.0, 1.0])
    robot.MoveL(p([374.000000, 174.400321, 610.000000, 0.000000, 90.000000, 0.000000]), [30.005768, 9.246934, -6.136218, 84.631745, -30.151638, -83.797873], [0.0, 0.0, 1.0])
    robot.MoveL(p([374.000000, -201.108593, 610.000000, 0.000000, 90.000000, 0.000000]), [-33.660539, 12.400929, -9.814293, -86.122958, -33.748102, 85.340395], [0.0, 0.0, 1.0])
    robot.MoveJ(p([374.000000, -0.000000, 610.000000, -0.000000, 90.000000, 0.000000]), [-0.000000, -0.836761, 4.599793, -0.000000, -3.763032, 0.000000], [0.0, 0.0, 1.0])
    robot.setTool(p([0.000000, 0.000000, 200.000000, 0.000000, 0.000000, 0.000000]), -1, r"""Paint gun""")
    robot.MoveC(p([374.000000, -0.000000, 610.000000, -0.000000, 90.000000, 0.000000]), [-0.000000, -0.836761, 4.599793, -0.000000, -3.763032, 0.000000], p([374.000000, -201.108593, 610.000000, 0.000000, 90.000000, 0.000000]), [-33.660539, 12.400929, -9.814293, -86.122958, -33.748102, 85.340395], [0.0, 0.0, 1.0], [0.0, 0.0, 1.0])
    robot.setZoneData(10.000)
    robot.setDO(5, 1)
    robot.setAO(5, 1)
    robot.waitDI(5, 1, 5000)
    robot.waitDI(5, 1, -1)
    robot.RunMessage(r"""Display message""")
    robot.ProgFinish(r"""ajkslfh""")
    for line in robot.PROG:
        print(line)
    if len(robot.LOG) > 0:
        mbox('Program generation LOG:\n\n' + robot.LOG)
    #input("Press Enter to close...")
    #return
    robot.ProgSave(".", "Program", True)
    for line in robot.PROG:
        print(line)
    if len(robot.LOG) > 0:
        mbox('Program generation LOG:\n\n' + robot.LOG)

    input("Press Enter to close...")


if __name__ == "__main__":
    """Function to call when the module is executed by itself: test"""
    test_post()
