package sygrtutorials;

import java.util.ArrayList;

import sygr.pots.extensions.PluginData;
import sygr.pots.extensions.PluginInterface;
import sygr.pots.extensions.PluginUtilInterface;
import sygr.pots.extensions.Pot;

public class T004OutConv implements PluginInterface{

	@Override
	public void execute(PluginData data, PluginUtilInterface util) {
		
		Boolean bwait = false;
		String soNumber = "";
		String uuid = "";
		
		try {
			bwait = (Boolean) data.transfer.get(0);
			if(!bwait) {
				soNumber = (String) data.transfer.get(1);
			}
			else {
				uuid = (String) data.transfer.get(1);
			}
		} catch (Exception e) {
			data.response.setAnswer("ERROR: data was not transferred from MsgConv");
			data.response.setStatus(406);
			return;
		}
		
		String resp = "Wait: " + bwait + System.lineSeparator();
		
		// If need to wait, wait and then find the Entity
		if(bwait) {
			
			boolean success = util.waitFor(data.result.messageid, 10, 1000, 0);
			if(!success) {
				resp = resp + "Waiting for async processing was unsuccessful." + System.lineSeparator();
			}
			else {
				ArrayList<String> potids = util.findPotIds("st", "SO with wait", 
						"uuid", uuid, 
						"", "", "", "", "", "", "", "", "", "", "ACTIVE");
				if(potids == null || potids.size() == 0) {
					resp = resp + "Cannot fid the posted Sales Order." + System.lineSeparator();
				}
				else {
					for(String potid: potids) {
						Pot order = util.getPot("st", potid);
						if(!(order == null)) {
							resp = resp + "SO number: " + order.getMatchval0() + System.lineSeparator();
						}
					}
				}
			}
			
		}
		
		resp = resp + "SO number: " + soNumber + System.lineSeparator();
		data.response.setAnswer(resp);
		data.response.setStatus(200);
		
		
		
	}

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

}
