#include <stdio.h>
#include <string.h>
#include "sap_moni.h"
#include "sap_moni_ccm.h"

#define ERROR 2

/*=======================================================================
  (C) Copyright SAP AG, 2002

         
 Author  : Dostert/SAP
 Project : Get data from R/3 using XMB
 Using   : RFCSDK 
 ========================================================================*/

void usage(char *progname) {
        #define BL printf(



         BL"Agent\n\n");
         BL"Syntax: %s <Template> <RFC-Template>\n\n",  progname     );


         BL"       <Template> defined in %s    \n", AGENT_INI_FILE  );
         BL"       <RFC-Template> defined in %s\n", AGENT_LOGIN_FILE  );
}



int main(int argc, char **argv) {
	int i,j;

	RFC_HANDLE rfc_handle;
	AlMoniHandle_T *MoniHandle; 
	int   NrOfMoniTempl;
//	
	AlMoniNode_T *nodes;
        unsigned int NrOfNodes;	

	char  templ_name[AL_MONI_MAX_TEMPL_NAME_LENGTH];
	int   highest_alert = 0;
	//char  *bg_color;	

	char node_info[255];

        //char tid_c[85];
	
	 //AlMoniTemplate_T *moni_templ;
        //BAPITNDEXT *tTreeNodes;


        //BAPITID    tid;
        //BAPIPAPROP Properties;

	if (argc < 3) {
		usage(argv[0]);
		return ERROR;
	}

	strcpy(templ_name, argv[1]);

	if ( sapmon_init(&MoniHandle, &NrOfMoniTempl) >=  AG_FIRST_ERROR) {
		printf("Could not initialize INI-File\n");
		return ERROR;
	}

	if( sapmon_connect(argv[2], &rfc_handle) >=  AG_FIRST_ERROR) {
		printf("Could not log on\n");
		return ERROR;
	}

	
	for (i = 0; i <  NrOfMoniTempl; i++) {
		if ( strcmp(sapmon_get_template_name(MoniHandle[i]), templ_name) != 0)
			continue;

		sapmon_request(&rfc_handle, &(MoniHandle[i]), 1 );
		sapmon_request_tree(MoniHandle[i], &nodes, &NrOfNodes);	

		for (j = 0; j < NrOfNodes; j++) {
                        if (nodes[j].Actualval > highest_alert)
                                highest_alert = nodes[j].Actualval;
			
			if (strcmp(nodes[j].Objectname,  nodes[j].Mtnameshrt) != 0) {

                                sprintf(node_info, "%s %s = %s", nodes[j].Objectname, nodes[j].Mtnameshrt, nodes[j].currentValue);
                        } else {

                                sprintf(node_info, "%s %s = <no value>", nodes[j].Objectname, nodes[j].Mtnameshrt);
                        }
			printf("%s\n", node_info); 
			

                }

	}

        //Nothing found
        if (NrOfNodes == 0) {
              highest_alert = 3;
              printf("No information gathered! System up?\n");
        }


	//Log off
	sapmon_disconnect(&rfc_handle);	
	if ( highest_alert < 1 || highest_alert > 3 ) {
                highest_alert = 4;
        }	
	return highest_alert -1;
}
