/*******************************************************************************
 *	TmsControlClient1.cpp	TMS API example code
 *			T.Barnaby,	BEAM Ltd,	2007-02-07
 *******************************************************************************
 *
 *	This is a very basic example of using the TmsApi from a clients perspective.
 *	It is designed to give an overview of using the API.
 */
#include <iostream>
#include <stdio.h>
#include <TmsD.h>
#include <TmsC.h>

using namespace Tms;
using namespace std;

const UInt32	tmsStateNum = 16;
const UInt32	tmsPickupNum = 40;

// Initialise and test the TMS system
BError tmsInit(TmsControl& tmsControl){
	BError			err;
	ConfigInfo		configInfo;
	BIter			i;
	BList<BError>		errorList;
	BList<NameValue>	nvList;
	BString			version;
	
	// Get Version
	if(err = tmsControl.getVersion(version)){
		return err.set(1, BString("Error: initialising TMS: ") + err.getString());
	}
	cout << "Version: " << version << "\n";
	
	// Initialise TMS system
	if(err = tmsControl.init()){
		return err.set(1, BString("Error: initialising TMS: ") + err.getString());
	}
	
	// Test TMS system
	if(err = tmsControl.test(errorList)){
		return err.set(1, BString("Error: testing TMS: ") + err.getString());
	}
	
	for(errorList.start(i); !errorList.isEnd(i); errorList.next(i)){
		cout << "Warning: " << errorList[i].getString() << "\n";
	}
	
	// Get Status of TMS system
	if(err = tmsControl.getStatus(nvList)){
		return err.set(1, BString("Error: getting status: ") + err.getString());
	}
	
	for(nvList.start(i); !nvList.isEnd(i); nvList.next(i)){
		cout << nvList[i].name << ":\t" << nvList[i].value << "\n";
	}

	return err;
}

int main(int argc, char** argv){
	BError			err;
	BString			host = "localhost";
	TmsControl		tmsControl;
	TmsProcess		tmsProcess;

	if(argc == 2)
		host = argv[1];

	// Connect to the Control service
	if(err = tmsControl.connectService(BString("//") + host + "/tmsControl")){
		cerr << "Error: " << err.getString() << "\n";
		return 1;
	}

	// Connect to the Process service
	if(err = tmsProcess.connectService(BString("//") + host + "/tmsProcess")){
		cerr << "Error: " << err.getString() << "\n";
		return 1;
	}

	// Initialise and test the TMS system. Normally carried out by a configuration
	// and test client program.
	if(err = tmsInit(tmsControl)){	
		cerr << "Error: " << err.getString() << "\n";
		return 1;
	}

	return 0;
}
