# Script for CODESYS project code generation
import scriptengine
import os
import sys

# Delete CODESYS temporary files
def RemoveCodesysTempFiles():
    for file in os.listdir(r"."):
        if '.opt' in file:
            os.remove(file)

# Open codesys project
print("Opening CODESYS project")
proj = projects.open(r"AutomationFirmware.project", primary = True)

# Get project application
app = proj.active_application

app.clean()

# Generate code for the application
print("Building CODESYS application")
app.generate_code()

# Get build messages from Build output
# errMess = system.get_messages("97f48d64-a2a3-4856-b640-75c046e37ea9")
output = system.get_message_categories()
print(output)
errMess = system.get_messages("97f48d64-a2a3-4856-b640-75c046e37ea9")
print(errMess[:])

# Check for errors
if not "ready for download" in errMess[-1]:
    print("Build failed with errors:")
    #print(errMess[2:-1])
    #print(errMess[:])
    RemoveCodesysTempFiles()
    sys.exit(2)

# Create boot application
print("Creating boot application")
app.create_boot_application("")

# Close file
print("Closing CODESYS project")
proj.close()

# Close codesys
print("Closing CODESYS")
system.exit()

# Remove temporary CODESYS files
RemoveCodesysTempFiles()

# Return OK
sys.exit(0)

# EOF
