#include <string.h>
#include "UA_PLC.h"

// UA_Client *client;

// u32 Connect(long *ConnectionHdl){
// 	UA_Client *c = UA_Client_new();
// 	UA_StatusCode flag = UA_ClientConfig_setDefault(UA_Client_getConfig(c));
// 	UA_ClientConfig *config=UA_Client_getConfig(c);
// 	if (flag == UA_STATUSCODE_GOOD) {
// 		flag=UA_Client_connect(c, "opc.tcp://localhost:4840");

// 	}else
// 	{
// 		UA_Client_delete(c);
// 		//memset(c,0,100);
// 		return flag;
// 	}
// 	client = c;
// 	*ConnectionHdl = (long *)c;
// 	printf("ConnectionHdl %lld \n",*ConnectionHdl);
// 	return flag;
// }

u32 UA_NodeGetHandleList(long ConnectionHdl,u16 NodeIDCount,UANodeID *NodeIDs,long *NodeHdls,u32 ErrorIDs[]){
	int i;
	u32 retval=0;
	UA_NodeId *NodeID=malloc(sizeof(UA_NodeId)*NodeIDCount);
	if(NodeIDCount>MAX_ELEMENTS_NODELIST){
		retval=0xA0000002;
		return retval;
	}

	for(i=0;i<NodeIDCount;i++){
        printf("\nNdeIDs[i].IdentifierType=%d,NodeIDs[i].NamespaceIndex=%d,NodeIDs[i].Identifier.length=%d, NodeIDs[i].Identifier.data=%s\n",
            NodeIDs[i].IdentifierType,   NodeIDs[i].NamespaceIndex,  NodeIDs[i].Identifier.length ,NodeIDs[i].Identifier.data );

		if(NodeIDs[i].IdentifierType>=0&&NodeIDs[i].IdentifierType<4){
			switch(NodeIDs[i].IdentifierType){
				case 0:NodeID[i]=UA_NODEID_NUMERIC(NodeIDs[i].NamespaceIndex,NodeIDs[i].Identifier.data);break;
				case 1:NodeID[i]=UA_NODEID_STRING(NodeIDs[i].NamespaceIndex,NodeIDs[i].Identifier.data);break;
				case 2:NodeID[i].identifierType=4;
						NodeID[i].identifier.string.data=NodeIDs[i].Identifier.data;
						NodeID[i].identifier.string.length=NodeIDs[i].Identifier.length;
						NodeID[i].namespaceIndex=NodeIDs[i].NamespaceIndex;break;
				case 3:NodeID[i]=UA_NODEID_BYTESTRING(NodeIDs[i].NamespaceIndex,NodeIDs[i].Identifier.data);break;
			}
			ErrorIDs[i]=0;
		}else{
			ErrorIDs[i]=0xA0000301;
			retval=ErrorIDs[i];
		}
		// NodeID[i].identifier.string.data=NodeIDs[i].Identifier.data;
		// NodeID[i].identifier.string.length=NodeIDs[i].Identifier.length;
		// NodeID[i].namespaceIndex=NodeIDs[i].NamespaceIndex;
		NodeHdls[i]=&NodeID[i];
		//UA_NodeId *NodeID1=malloc(sizeof(UA_NodeId)*NodeIDCount);
		//UA_NodeId_delete(&NodeID[i]);
	}

	return retval;

}

void Browser(){
	
}

int main(int argc, char *argv[]) {
	
    // long connecthdl;
	// Connect(&connecthdl);
	UA_Client *client = UA_Client_new();
    UA_ClientConfig_setDefault(UA_Client_getConfig(client));
    UA_StatusCode retval = UA_Client_connect(client, "opc.tcp://localhost:4840");
    if(retval != UA_STATUSCODE_GOOD) {
        UA_Client_delete(client);
        return (int)retval;
    }
	long *connecthdl = (long*)client;
	UANodeID nodes[4];
	long nodeHdls[4] = {0};
	u32 errors[4];
	printf("Browsing nodes in objects folder:\n");
    UA_BrowseRequest bReq;
    UA_BrowseRequest_init(&bReq);
    bReq.requestedMaxReferencesPerNode = 0;
    bReq.nodesToBrowse = UA_BrowseDescription_new();
    bReq.nodesToBrowseSize = 1;
    bReq.nodesToBrowse[0].nodeId = UA_NODEID_NUMERIC(0, UA_NS0ID_OBJECTSFOLDER); /* browse objects folder */
    bReq.nodesToBrowse[0].resultMask = UA_BROWSERESULTMASK_ALL; /* return everything */
    UA_BrowseResponse bResp = UA_Client_Service_browse(client, bReq);
	printf("\n\n 0x%08x \n\n",bResp.responseHeader.serviceResult);
    printf("%-9s %-16s %-16s %-16s\n", "NAMESPACE", "NODEID", "BROWSE NAME", "DISPLAY NAME");
    for(size_t i = 0; i < bResp.resultsSize; ++i) {
        for(size_t j = 0; j < bResp.results[i].referencesSize; ++j) {
            UA_ReferenceDescription *ref = &(bResp.results[i].references[j]);
            if(ref->nodeId.nodeId.identifierType == UA_NODEIDTYPE_NUMERIC) {
                printf("%-9u %-16u %-16.*s %-16.*s\n", ref->nodeId.nodeId.namespaceIndex,
                       ref->nodeId.nodeId.identifier.numeric, (int)ref->browseName.name.length,
                       ref->browseName.name.data, (int)ref->displayName.text.length,
                       ref->displayName.text.data);
            } else if(ref->nodeId.nodeId.identifierType == UA_NODEIDTYPE_STRING) {
                printf("%-9u %-16.*s %-16.*s %-16.*s\n", ref->nodeId.nodeId.namespaceIndex,
                       (int)ref->nodeId.nodeId.identifier.string.length,
                       ref->nodeId.nodeId.identifier.string.data,
                       (int)ref->browseName.name.length, ref->browseName.name.data,
                       (int)ref->displayName.text.length, ref->displayName.text.data);
            }

			printf("%lld",ref->nodeId.nodeId.identifier.numeric);

			nodes[j].Identifier.length = ref->nodeId.nodeId.identifier.string.length;
			if(nodes[j].Identifier.length > 0) {
    			nodes[j].Identifier.data = (u8*)malloc(nodes[j].Identifier.length);
				snprintf(nodes[j].Identifier.data, nodes[j].Identifier.length, "%lld", (long long)ref->nodeId.nodeId.identifier.numeric);
    			
			}
			nodes[j].IdentifierType = ref->nodeId.nodeId.identifierType;
			nodes[j].NamespaceIndex = ref->nodeId.nodeId.namespaceIndex;
            /* TODO: distinguish further types */
        }
    }
    UA_BrowseRequest_clear(&bReq);
    UA_BrowseResponse_clear(&bResp);

	UA_NodeGetHandleList(*connecthdl,4,nodes,nodeHdls,errors);

	printf("%d\n",nodeHdls[0]);
    /* Clean up */
    UA_Client_disconnect(client);
    UA_Client_delete(client);
	
	
}