# -*- coding: UTF-8 -*-
# Copyright 2015-2023 - RoboDK Inc. - https://robodk.com/
#
# This is a compiled post processor. Please contact us at info@robodk.com if you need access to the source code of this post processor.
#
# This file loads the compiled version of the RoboDK post processor for:
#   Mitsubishi robot controllers
# 
# More information about RoboDK Post Processors and Offline Programming:
#     https://robodk.com/help#PostProcessor
#     https://robodk.com/doc/en/PythonAPI/postprocessor.html
# ----------------------------------------------------

import sys
import os

#Needed to make the robodk generated code work
import math
from robodk import *

# Detect Python version and post processor
print("Using Python version: " + str(sys.version_info))
path_app = os.path.dirname(__file__).replace(os.sep,"/")
print("RoboDK Post Processor: " + path_app)

# Check if the post is compatible with the Python version
version_str = str(sys.version_info[0]) + str(sys.version_info[1])
path_library = path_app + '/v' + version_str
if not os.path.isdir(path_library):
    msg = "Invalid Python version or post processor not found. Make sure you are using a supported Python version: " + path_library
    msg += "\nSelect Tools-Options-Python and select a supported Python version"
    print(msg)
    raise Exception(msg)

# Load the post processor
exec("from v" + version_str + ".Mitsubishi import RobotPost as BasePost")

class RobotPost(BasePost):
    """Robot post object"""
    # ----------------------------------------------------
    # Default Digital Output module (usually OUT or M_OUT)
    DOUT_STRING = "M_OUT"    

    # Default Analog Output module (usually OUT or M_OUT)
    AOUT_STRING = "OUT"    

    # Set the default configuration flag (7,0):
    #FLAG_CONFIG = '6'  # Set to 6 to use front/elbow up/non flip
    #FLAG_CONFIG = '7'  # Set to 7 to use front/elbow up/flip
    #FLAG_CONFIG = ''   # Set an empty string to leave it unset
    # Set to None to let RoboDK calculate it automatically
    FLAG_CONFIG = None    

    # Set the default turn flag (7,0):
    #FLAG_TURNS = '0'  # Closest to 0
    # Set to None to let RoboDK calculate it automatically
    FLAG_TURNS = None    


    
    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"""
        import os
        comClass = RobotCom()
        retVal = comClass.connect(robot_ip)
        if (retVal == False):
            raise ValueError('Error connecting to robot: ' + robot_ip)

        if isinstance(self.PROG_FILES, list):
            self.PROG_FILES = [self.PROG_FILES] 

        for progPath in self.PROG_FILES:
            if progPath.lower().endswith(".csv"):
                print("Warning: Sending CSV files is not supported")
                continue

            fileName = os.path.basename(progPath)
            fileName = os.path.splitext(fileName)[0]
            #fileName = "MRL"
            comClass.Run("1;1;FDEL"+fileName, False)
            comClass.Run("1;1;NEW", False)
            comClass.Run("1;1;LOAD="+fileName, False)

            curFile = open(progPath, 'r')
            curLines = curFile.readlines()
            count = 1
            for line in curLines:
                comClass.Run("1;1;EDATA " + str(count) + line, False)
                count += 1

            #ROBOT_TOOL_STR = '0.000,0.000,0.000,0.000,0.000,0.000'
            #comClass.Run("1;1;EDATA 1 Base (0.000,0.000,0.000,0.000,0.000,0.000)")
            #comClass.Run("1;1;EDATA 2 Tool (" + ROBOT_TOOL_STR + ")")
            #comClass.Run('1;1;EDATA 3 ACCEL %.3f' % comClass.accel_percent_joints , False)
            #comClass.Run('1;1;EDATA 4 SPD %.3f' % comClass.speed_mms , False)

            comClass.Run("1;1;SAVE", False)
            comClass.Run("1;1;RSTPRG", False)
            comClass.Run("1;1;PRGLOAD="+fileName, False)
            comClass.Run("1;1;RSTPRG", False)


        print(comClass)
        #UploadFTP(self.PROG_FILES, robot_ip, remote_path, ftp_user, ftp_pass)

if __name__== "__main__":
    exec("from v" + version_str + ".Mitsubishi import test_post")
    test_post()

