package sygrtutorials;

import java.util.ArrayList;

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;
import sygr.pots.extensions.Uuid;

public class T004MsgConv implements PluginInterface{

	@Override
	public void execute(PluginData data, PluginUtilInterface util) {
		
		// Read the XML message
		T004SoHeader so = new T004SoHeader();
		try {
			so = data.xmlMapper.readValue(data.messageIn.getContent(), T004SoHeader.class);
		} catch (Exception e) {
			util.log("ERROR: content could not read.");
			return;
		}
		
		// We send the information whether to wait or not to the Output Converter
		Boolean bwait = Boolean.valueOf(so.wait);
		data.transfer.add(bwait);
		
		String soNumber = "";
		String uuid = "";
		if(so.wait == false) {
			soNumber = HelpUtil.getNextSoNumber(util);
			data.transfer.add(soNumber);
		}
		else {
			uuid = Uuid.getUuid();
			data.transfer.add(uuid);
		}
		
		// And now compose our Sales Order request in form of a Creator object
		Creator creator = new Creator();
		creator.setType("SO initial");
		creator.setMatchkey0("so_number");
		creator.setMatchval0(soNumber);
		creator.setMatchkey1("uuid");
		creator.setMatchval1(uuid);
		creator.setMatchkey2("customer");
		creator.setMatchval2(so.customer);
		
		creator.setInitplugin("asyncsoinit");
		
		// Create the items
		Attr flexi = new Attr();
		int itemno = 1000;
		for(T004SoItem soi: so.items) {
			itemno += 10;
			String item = "Item " + String.valueOf(itemno) + ".";
			util.setNodeValue(flexi, soi.material, item + "material");
			util.setNodeValue(flexi, String.valueOf(soi.quantity), item + "quantity");
			util.setNodeValue(flexi, soi.uom, item + "uom");
		}
		creator.setAttr(flexi);
		
		// And add to the output message
		data.messageOut.addCreator(creator);
		
	}

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

}
