#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_NodeGetInformation(long ConnectionHdl,UANodeID NodeID,UANodeInformation *NodeInfo,u32 ErrorIDs[]){
	UA_Client *c = (UA_Client*)ConnectionHdl;
	if (c == NULL) {
    	fprintf(stderr, "Invalid UA_Client pointer\n");
    	return UA_STATUSCODE_BADUNEXPECTEDERROR; // 返回错误码
	}
	u32 retval,ret=0;

	printf("\n\n %s \n\n",NodeID.Identifier.data);

	//UA_NodeId NODEID=UA_NODEID_STRING(NodeID.NamespaceIndex,NodeID.Identifier.data);
	UA_NodeId NODEID=UA_NODEID_NUMERIC(NodeID.NamespaceIndex,atoll(NodeID.Identifier.data));
	
	// NODEID.namespaceIndex = NodeID.NamespaceIndex;
	// if(NodeID.IdentifierType>=0&&NodeID.IdentifierType<4){
	// 		switch(NodeID.IdentifierType){
	// 			case 0:NODEID.identifierType=0;
	// 			case 1:NODEID.identifierType=3;
	// 			case 2:NODEID.identifierType=4;
	// 			case 3:NODEID.identifierType=5;
	// 		}
	// 		ret=0;
	// 	}else{
	// 		ret=0xA0000301;
	// 	}
	// NODEID.identifier.string = UA_STRING(NodeID.Identifier.data);
	UA_NodeClass outNodeClass;
	UA_NodeClass_init(&outNodeClass);
	retval=UA_Client_readNodeClassAttribute(c,NODEID,&outNodeClass);
	if(retval!=0){
		ErrorIDs[0]=retval;
		ret=retval;
	}
	u32 temp =outNodeClass;
	NodeInfo->NodeClass=temp;
	UA_NodeClass_clear(&outNodeClass);

	UA_QualifiedName outBrowseName;
	UA_QualifiedName_init(&outBrowseName);
	retval=UA_Client_readBrowseNameAttribute(c,NODEID,&outBrowseName);
	if(retval!=0){
		fprintf(stderr, "Failed to read BrowseName: %s\n", UA_StatusCode_name(retval));
		ErrorIDs[1]=retval;
		ret=retval;
		return ret;
	}
	NodeInfo->BrowseName.NamespaceIndex=outBrowseName.namespaceIndex;
	NodeInfo->BrowseName.Name.length=outBrowseName.name.length;
	NodeInfo->BrowseName.Name.data=outBrowseName.name.data;
	printf("\n\n %s \n\n",outBrowseName.name.data);
	UA_QualifiedName_clear(&outBrowseName);

	UA_LocalizedText outDisplayName;
	UA_LocalizedText_init(&outDisplayName);
	retval=UA_Client_readDisplayNameAttribute(c,NODEID,&outDisplayName);
	if(retval!=0){
		ErrorIDs[2]=retval;
		ret=retval;
	}
	NodeInfo->DisplayName.Locale=outDisplayName.locale.data;
	NodeInfo->DisplayName.Text.length=outDisplayName.text.length;
	NodeInfo->DisplayName.Text.data=outDisplayName.text.data;
	UA_LocalizedText_clear(&outDisplayName);

	UA_LocalizedText outDescription;
	UA_LocalizedText_init(&outDescription);
	retval=UA_Client_readDescriptionAttribute(c,NODEID,&outDescription);
	if(retval!=0){
		ErrorIDs[3]=retval;
		ret=retval;
	}
	NodeInfo->Description.Locale=outDescription.locale.data;
	NodeInfo->Description.Text.length=outDescription.text.length;
	NodeInfo->Description.Text.data=outDescription.text.data;
	UA_LocalizedText_clear(&outDescription);

	UA_UInt32 outWriteMask;
	UA_UInt32_init(&outWriteMask);
	retval=UA_Client_readWriteMaskAttribute(c,NODEID,&outWriteMask);
	if(retval!=0){
		ErrorIDs[4]=retval;
		ret=retval;
	}
	NodeInfo->WriteMask=outWriteMask;
	UA_UInt32_clear(&outWriteMask);

	UA_UInt32 outUserWriteMask;
	UA_UInt32_init(&outUserWriteMask);
	retval=UA_Client_readUserWriteMaskAttribute(c,NODEID,&outUserWriteMask);
	if(retval!=0){
		ErrorIDs[5]=retval;
		ret=retval;
	}
	NodeInfo->UserWriteMask=outUserWriteMask;
	UA_UInt32_clear(&outUserWriteMask);

	UA_Boolean outIsAbstract;
	UA_Boolean_init(&outIsAbstract);
	retval=UA_Client_readIsAbstractAttribute(c,NODEID,&outIsAbstract);
	if(retval!=0){
		ErrorIDs[6]=retval;
		//ret=retval;
	}
	NodeInfo->IsAbstract=outIsAbstract;
	UA_Boolean_clear(&outIsAbstract);

	UA_Boolean outSymmetric;
	UA_Boolean_init(&outSymmetric);
	retval=UA_Client_readSymmetricAttribute(c,NODEID,&outSymmetric);
	if(retval!=0){
		ErrorIDs[7]=retval;
		//ret=retval;
	}
	NodeInfo->Symmetric=outSymmetric;
	UA_Boolean_clear(&outSymmetric);

	UA_LocalizedText outInverseName;
	UA_LocalizedText_init(&outInverseName);
	retval=UA_Client_readInverseNameAttribute(c,NODEID,&outInverseName);
	if(retval!=0){
		ErrorIDs[8]=retval;
		//ret=retval;
	}
	NodeInfo->InverseName.length=outInverseName.text.length;
	NodeInfo->InverseName.data=outInverseName.text.data;
	UA_LocalizedText_clear(&outInverseName);

	UA_Boolean outContainsNoLoops;
	UA_Boolean_init(&outContainsNoLoops);
	retval=UA_Client_readContainsNoLoopsAttribute(c,NODEID,&outContainsNoLoops);
	if(retval!=0){
		ErrorIDs[9]=retval;
		//ret=retval;
	}
	NodeInfo->ContainsNoLoops=outContainsNoLoops;
	UA_Boolean_clear(&outContainsNoLoops);

	UA_Byte outEventNotifier;
	UA_Byte_init(&outEventNotifier);
	retval=UA_Client_readEventNotifierAttribute(c,NODEID,&outEventNotifier);
	if(retval!=0){
		ErrorIDs[10]=retval;
		//ret=retval;
	}
	NodeInfo->EventNotifier=outEventNotifier;
	UA_Byte_clear(&outEventNotifier);

	UA_NodeId outDataType;
	UA_NodeId_init(&outDataType);
	retval=UA_Client_readDataTypeAttribute(c,NODEID,&outDataType);
	if(retval!=0){
		ErrorIDs[11]=retval;
		ret=retval;
	}
	NodeInfo->DataType.NamespaceIndex=outDataType.namespaceIndex;
	NodeInfo->DataType.IdentifierType=outDataType.identifierType;
	NodeInfo->DataType.Identifier.length=outDataType.identifier.string.length;
	NodeInfo->DataType.Identifier.data=outDataType.identifier.string.data;
	UA_NodeId_clear(&outDataType);

	UA_Int32 outValueRank;
	UA_Int32_init(&outValueRank);
	retval=UA_Client_readValueRankAttribute(c,NODEID,&outValueRank);
	if(retval!=0){
		ErrorIDs[12]=retval;
		ret=retval;
	}
	NodeInfo->ValueRank=outValueRank;
	UA_Int32_clear(&outValueRank);

	UA_UInt32 outArrayDimensions[MAX_ELEMENTS_ARRAYDIMENSION];
	//UA_UInt32_init(*outArrayDimensions);
	int size;
	retval=UA_Client_readArrayDimensionsAttribute(c,NODEID,&size,outArrayDimensions);
	if(retval!=0){
		ErrorIDs[13]=retval;
		ret=retval;
	}
	for(int i=0;i<MAX_ELEMENTS_ARRAYDIMENSION;i++){
		NodeInfo->ArrayDimension[i]=outArrayDimensions[i];
	}


	UA_Byte outAccessLevel;
	UA_Byte_init(&outAccessLevel);
	retval=UA_Client_readAccessLevelAttribute(c,NODEID,&outAccessLevel);
	if(retval!=0){
		ErrorIDs[14]=retval;
		ret=retval;
	}
	NodeInfo->AccessLevel=outAccessLevel;

	UA_Byte outUserAccessLevel;
	UA_Byte_init(&outUserAccessLevel);
	retval=UA_Client_readUserAccessLevelAttribute(c,NODEID,&outUserAccessLevel);
	if(retval!=0){
		ErrorIDs[15]=retval;
		ret=retval;
	}
	NodeInfo->UserAccessLevel=outUserAccessLevel;

	UA_Double outMinSamplingInterval;
	UA_Double_init(&outMinSamplingInterval);
	retval=UA_Client_readMinimumSamplingIntervalAttribute(c,NODEID,&outMinSamplingInterval);
	if(retval!=0){
		ErrorIDs[16]=retval;
		ret=retval;
	}
	NodeInfo->MinimumSamplingInterval=outMinSamplingInterval;

	UA_Boolean outHistorizing;
	UA_Boolean_init(&outHistorizing);
	retval=UA_Client_readHistorizingAttribute(c,NODEID,&outHistorizing);
	if(retval!=0){
		ErrorIDs[17]=retval;
		ret=retval;
	}
	NodeInfo->Historizing=outHistorizing;

	UA_Boolean outExecutable;
	UA_Boolean_init(&outExecutable);
	retval=UA_Client_readExecutableAttribute(c,NODEID,&outExecutable);
	if(retval!=0){
		ErrorIDs[18]=retval;
		//ret=retval;
	}
	NodeInfo->Executable=outExecutable;

	UA_Boolean outUserExecutable;
	UA_Boolean_init(&outUserExecutable);
	retval=UA_Client_readUserExecutableAttribute(c,NODEID,&outUserExecutable);
	if(retval!=0){
		ErrorIDs[19]=retval;
		//ret=retval;
	}
	NodeInfo->UserExecutable=outUserExecutable;

	return ret;
}

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 hdl = (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);

	UANodeInformation *nodeinfo = (UANodeInformation*)malloc(sizeof(UANodeInformation));
	UA_NodeGetInformation(hdl,nodes[1],nodeinfo,errors);

    /* Clean up */
    UA_Client_disconnect(client);
    UA_Client_delete(client);
	
	
}