from __future__ import print_function
import os
import unittest
import time

# Read / Write Variable without opening codesys
# this file will be called from a batch file.



# Project name will be set with batch and transfered via enviroment variable
#######################
# Open Codesys project
#######################
def openProject(PROJECT):
	print(" opening project: ", PROJECT)
	proj = projects.open(PROJECT)

##############################
# creating online application
##############################
def createOnlineApp():
	print(scriptName, ": creating online application ...")
	# onlineApp = online.create_online_application(proj.active_application)

	# if it is already online manually
	global onlineApp
	onlineApp = online.create_online_application()

##############################
# Lgoin
##############################
def login():
	print(scriptName, ": login ...")
	global onlineApp
	onlineApp.login(OnlineChangeOption.Try, True)

	if not onlineApp.application_state == ApplicationState.run:
		print(scriptName, ": Run Application")
		onlineApp.start()
	else:
		print(scriptName, ": Application is already running")

##############################################################
# input and output are changed as list instead of dictionary
###############################################################

class FB_GetResource(object):
	def __init__(self):
		self.input = {"strIndex":"", "strSubIndex":""}
		self.output = []
		
		self.PLC_I_VAR_STR_INDEX = "TestGetResource.strIndex"
		self.PLC_I_VAR_STR_SUBINDEX = "TestGetResource.strSubIndex"
		self.PLC_O_VAR_INDEX = "TestGetResource.StResource.Index"
		self.PLC_O_VAR_SUBINDEX = "TestGetResource.StResource.SubIndex"
		
	# take input value
	def Inputs(self,strIndex,strSubIndex):
		self.input["strIndex"] = strIndex
		self.input["strSubIndex"] = strSubIndex
	
	# read value	
	def ReadVar(self, var):
		Value = onlineApp.read_value(var)	# INT#5
		# print(" type of Value is:", type(Value))
		#print("variables to read:",var)
		print(" value of %s is: %s"% (var, Value))
		return Value
	
	# Write a string variable	
	def WriteStrVar(self, sVar, Value):
		ValueToWrite = "'" + str(Value) + "'"
		onlineApp.set_prepared_value(sVar, ValueToWrite)
	
	# Write int and real variable
	def WriteVar():
		ValueToWrite = str(iValue)
		onlineApp.set_prepared_value(var, ValueToWrite)
	
	# write inputs
	def WriteInputs(self):
		self.WriteStrVar(self.PLC_I_VAR_STR_INDEX, self.input["strIndex"])
		self.WriteStrVar(self.PLC_I_VAR_STR_SUBINDEX, self.input["strSubIndex"])
		onlineApp.write_prepared_values()
		
	# read outputs
	def ReadOutputs(self):
		# self.output["Index"] = self.ReadVar(self.PLC_O_VAR_INDEX)
		# self.output["SubIndex"] = self.ReadVar(self.PLC_O_VAR_SUBINDEX)
		self.output = []
		self.output.append(self.ReadVar(self.PLC_O_VAR_INDEX))
		self.output.append(self.ReadVar(self.PLC_O_VAR_SUBINDEX))
		
		print(" the output is:", self.output)
	
	# test
	def Test(self, Index, SubIndex):
		self.Inputs(Index,SubIndex)
		self.WriteInputs()
		time.sleep(0.5)	# system.delay(xx ms) doesn't work it the script is called by another script
		self.ReadOutputs()
		return self.output
	

getResource=FB_GetResource();
# getResource.Test(2,3)

# scriptname
scriptName = os.path.basename(__file__)

def readData():
	""" read testing data from file"""
	sfile = os.path.dirname(os.path.realpath(__file__)) +"/"+ "testdata.txt"

	print(sfile)

	with open(sfile) as f:
		lines = f.readlines()

	# print(lines)
	arrInput = []
	arrOutput = []

	for line in lines:
		# print(line)
		sInput, sOutput = line.split(";")
		# print("input: %s. output: %s" %(sInput, sOutput))
		Input = sInput.split()
		Output = sOutput.split()
		# print("input: ", Input)
		# print("output:", Output)
		arrInput.append(Input)
		arrOutput.append(Output)
	return arrInput, arrOutput


class Test(unittest.TestCase):
	def test_basic_addition(self):
		print(scriptName, ": unit test running ...")
		#result = getResource.Test(2,2)
		#expect = ["INDEX.INPUT", "UINT#2"]
		#self.failUnlessEqual(result,expect)
		
		global arrInput
		global arrOutput
		i = 1
		for input, output in zip(arrInput, arrOutput):
			result = getResource.Test(input[0],input[1])
			expect = output
			print("test case: ",i, "input: ", input, ",", "expected: ", expect, ",", "actual result: ", result)
			self.failUnlessEqual(result,expect)
			i+=1
		

if __name__ == '__main__':
	print("%s: ####### script is running as main ##############" %(scriptName))
	global onlineApp
	createOnlineApp()
	login()
	
	global arrInput
	global arrOutput
	
	arrInput, arrOutput = readData()
	
	unittest.main()

# starting test fom another script	
def StartTest(App):

	global onlineApp
	onlineApp = App
	print("online applicaiton is:", onlineApp)
	
	global arrInput
	global arrOutput
	
	arrInput, arrOutput = readData()
	unittest.main()
