# -*- coding: iso-8859-1 -*-

from __future__ import print_function

import sys



# defines aus clPLCC.h
PLCLOADOPTION_IMPORT =           0x0010
PLCLOADOPTION_NOERRORMSG =       0x0020
# PLCLOADOPTION_START_IECGATEWAY = 0x0040
PLCLOADOPTION_PLCHANDLER =       0x0080
PLCLOADOPTION_ONLINECHANGE =     0x0100    # nur Codesys3
PLCLOADOPTION_CREATEBOOTPRJ =    0x0200    # nur Codesys3



#
# Ausgabe-Funktion
#
def MessageBox(text):

    system.ui.info(text)



#
# Import Code in IEC
#
def ImportCodeInIEC(iecproject, iecapplication):

    # rename project",
    iecproject.save_as(".\\TmpImport.project")

    # create the import reporter
    class Reporter(ImportReporter):
        def added(self, obj):
            print("Import added: ", obj)
        def replaced(self, obj):
            print("Import replaced: ", obj)
        def skipped(self, obj):
            print("Import skipped: ", obj)
        def resolve_conflict(self, obj):
            MessageBox("Konflikt beim Import")
            return ConflictResolve.Replace
        def warning(self, message):
            MessageBox("Warning beim Import")
            system.write_message(Severity.Warning, message)
        def error(self, message):
            MessageBox("Error beim Import")
            system.write_message(Severity.Error, message)
        @property
        def aborting(self):
            return False

    # create the importer instance
    reporter = Reporter()

    # import the data into the project
    iecapplication.import_xml(reporter, "fb1.xml")

    # save project
    iecproject.save()



#
# Main
#

# Check count arguments
if len(sys.argv) != 3:
    MessageBox("Anzahl Argumente (%u) ist nicht 3" %len(sys.argv))
    for arg in sys.argv:
        MessageBox(arg)
    system.exit()

try:
    loadoption = int(sys.argv[2])
except:    
    MessageBox("Argument[2]: " + sys.argv[2] + " ist keine Zahl")
    system.exit()

# Close all projects
while len(projects.all) > 0:
    projects.all[0].close()

# opens project
#proj = projects.open(r"C:\Projekte\SEWTestLounge\Data\CoDeSys\GenC\TestSVN4.project")
proj = projects.open(sys.argv[1])

# set this project to active application
app = proj.active_application
onlineapp = online.create_online_application(app)

# import code in IEC
if (loadoption & PLCLOADOPTION_IMPORT) != 0:
    ImportCodeInIEC(proj, app);



#
# ...
#
controllerlist = projects.primary.find("Device", True)
if controllerlist.Count == 0:
    MessageBox("""Kein Gerät mit dem Namen "Device" gefunden""")
    system.exit()

devicegw= controllerlist[0].get_gateway()
devicead= controllerlist[0].get_address()
# system.ui.info(devicegw.__str__())
# system.ui.info(devicead)
# controllerlist[0].set_gateway_and_address(devicegw, devicead)



# login to device
if (loadoption & PLCLOADOPTION_ONLINECHANGE) != 0:
    onlineapp.login(OnlineChangeOption.Force, True)
else:
    onlineapp.login(OnlineChangeOption.Never, True)

# create boot app?
if (loadoption & PLCLOADOPTION_CREATEBOOTPRJ) != 0:
    onlineapp.create_boot_application()

# set status of application to run, if not in run
if not onlineapp.application_state == ApplicationState.run:
    onlineapp.start()

# wait 1 second
system.delay(1000)

# log out from device and close project
onlineapp.logout()
system.delay(8000)
proj.close()
system.exit()
