# Create fixed Text IDOC interface file using mapping rules from idocmapout.txt

import os
import time
import datetime

# Get Current Path
dir_path = os.path.dirname(os.path.realpath(__file__))

# Main Processing
def main():
	mapSegment = []
	mapLength = []
	mapMap = []
	
	outSegments = []
	lineArray = []
	detailArray = []
	inArray = []
	
# Read IDOC Mapping Values
	file_path_map = os.path.join(dir_path, 'idocmapout.txt')
	iDocMap = open(file_path_map,"r")
	for line in iDocMap:
		line = line.replace('\n','')
		mapSegment.append(line.split(":")[0])
		mapLength.append(line.split(":")[1])
		mapMap.append(line.split(":")[2])
	iDocMap.close()
# open output file
	file_path = os.path.join(dir_path, '../vimsout/idoctranout.txt')
	iDocTranOut = open(file_path,"w")	
# Read IDOC Transaction
	file_path = os.path.join(dir_path, '../vimsin/idoctranin.txt')
	iDocTran = open(file_path,"r")
	l = 0
	outSegments.clear()
	lineType = ""
	segmentType = ""
	for line in iDocTran:
		lineStr = ""
		line = line.replace('\n','')
		print("LINE:"+line)
# Parse Out Segment name & data
		segment = line.split(">") [0];
		inStr = line.split(">") [1];		
		
# try to find matching segment map in segment array
		i = 0
		while (i < len(mapSegment)):
			if (segment.strip() == mapSegment[i].strip()):
# Create / pad Output Data Array
				l = 0
				lineArray.clear()
				while (l < int(mapLength[i])):
					lineArray.append("")
					l=l+1
# Parse Out Mapping Values
				detailArray = mapMap[i].split(",")
				d = 0			
# Parse out Input Data to Field_Name & Field_Value
				inArray = inStr.split(",")
				c = 0
# Split out Inout Data Field Name & Value
				while (c < len(inArray)):
					fldName = inArray[c].split(":") [0]
					fldData = inArray[c].split(":") [1]
					f = 0
# Look for matching field name in mapping table
					while (f < len(detailArray)):
						if (fldName.strip() == detailArray[f].strip()):
							l = 0
# map the field value to the fixed text position
							while (l < len(fldData)):
#								print("TEST:",int(detailArray[f+1])+l,"-",fldData[l:l+1])
								lineArray[int(detailArray[f+1])+l] = fldData[l:l+1]
								l = l+1
							lineStr = "";
							l = 0
# convert list to string
							while (l < len(lineArray)):
								if (lineArray[l] == ""):
									lineStr = lineStr+" "
								else:
									lineStr = lineStr+lineArray[l]
#								print("TEST:",l)
								l=l+1
#							print("TEST-",lineStr)	
							break
						f = f+1
					c = c+1
			p = len(lineStr)
			while (p < int(mapLength[i])):
				lineStr += " ";
				p = p+1
			i = i+1
		print ("Data: "+lineStr)
		iDocTranOut.write(lineStr)
#			wf.append(lineStr)
		
	iDocTran.close()
	iDocTranOut.close()

if __name__ == '__main__':
		main()