package sygrtutorials;

import java.util.ArrayList;
import java.util.Collections;

import sygr.pots.extensions.Attr;
import sygr.pots.extensions.Creator;
import sygr.pots.extensions.PluginData;
import sygr.pots.extensions.PluginInterface;
import sygr.pots.extensions.PluginUtilInterface;

public class T002MsgConv implements PluginInterface{

	@Override
	public void execute(PluginData data, PluginUtilInterface util) {
		
		ArrayList<String> lines = new ArrayList<>();
		try {
			String[] pts = data.messageIn.getContent().split(System.lineSeparator());
			Collections.addAll(lines, pts);
		} catch (Exception e) {
			util.log("ERROR: content could not read.");
			return;
		}
		
		util.log("Read " + lines.size() + " lines.");
		
		for(String line: lines) {
			
			util.log("Processing: " + line);
			
			// Our separator will be the ";"
			try {
				String[] pts = line.split(";");
				if(pts == null || pts.length < 4) continue;
				
				// Create a new Sales Order using the Creator class
				Creator creator = new Creator();
				
				// Set the Entity Model
				creator.setType("My test sales orders");
				
				// Set the matching
				creator.setMatchkey0("sales order");
				creator.setMatchval0(pts[0]);
				
				// Create the transactional data
				Attr attr = new Attr();
				// Add the values
				util.setNodeValue(attr, pts[1], "material");
				util.setNodeValue(attr, pts[2], "requested delivery date");
				util.setNodeValue(attr, pts[3], "requested quantity");
				util.setNodeValue(attr, "0", "requested quantity.received quantity");
				// And pass it to the creator
				creator.setAttr(attr);
				
				// Add to the returning data
				data.messageOut.addCreator(creator);
				
				
			} catch (Exception e) {
				util.log("ERROR: line is not understandable: " + line);
				return;
			}
		}
		
	}

	@Override
	public void reloadConfig(ArrayList<String> changes, PluginUtilInterface util) {
		
	}

}
