#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;

}

u32 UA_ReadList(long ConnectionHdl,u16 NodeHdlCount,long *NodeHdls,UANodeAdditionalInfo *NodeAddInfos,UA_Value *variables,u32 ErrorIDs[]){
	UA_Client *c = (UA_Client*)ConnectionHdl;
	int i;
	u32 retval;
 	UA_ReadValueId item[NodeHdlCount];
	if(NodeHdlCount>MAX_ELEMENTS_NODELIST){
		retval=0xA0000002;
	}
	else
    {
        for(i=0;i<NodeHdlCount;i++){
            UA_ReadValueId_init(&item[i]);
            item[i].nodeId = *(UA_NodeId*)NodeHdls[i];
            //item[i].nodeId.identifier.numeric = NodeHdls[i];//zjy 20240910
            item[i].attributeId = NodeAddInfos[i].AttributeID;
            //item[i].nodeId.namespaceIndex = 1;
            printf("------------#2------NodeHdls[i] = %ld ,item[i].nodeId = %d,item[i].attributeId=%d,item[i].nodeId.namespaceIndex=%d-\n",
               NodeHdls[i],item[i].nodeId.identifier.string.length,item[i].attributeId,item[i].nodeId.namespaceIndex);
        }
        UA_ReadRequest request;
        UA_ReadRequest_init(&request);
        request.nodesToRead = &item[0];
        request.nodesToReadSize = 1;
        UA_ReadResponse response = UA_Client_Service_read(c, request);
        retval = response.responseHeader.serviceResult;
        if(retval == UA_STATUSCODE_GOOD)
        {
            printf("------------#3---------------\n");
            if(response.resultsSize==NodeHdlCount)
            {
                printf("------------#4---------------\n");
                for (i = 0; i < NodeHdlCount; i++)
                {
                    ErrorIDs[i]=response.results[i].status;
                }
                retval = 0 ;
                for(i=0;i<NodeHdlCount;i++)
                {
                    if(ErrorIDs[i]==UA_STATUSCODE_GOOD)
                    {
                        printf("------------#5---------------\n");
                        UA_DataValue res = response.results[i];
                        if(!res.hasValue)
                        {
                            printf("------------#6---------------\n");
                            UA_ReadResponse_clear(&response);
                            retval =  UA_STATUSCODE_BADUNEXPECTEDERROR;
                        }
						else
						{
  							if(NodeAddInfos[i].AttributeID == UA_ATTRIBUTEID_VALUE)
							{
  								//UA_Variant *out=malloc(sizeof(UA_Variant));
								UA_Variant out;
								//memcpy(&out, &res.value, sizeof(UA_Variant));
								//UA_Variant_init(&res.value);
								//variables[i].data =res.value.data;
								long temp ;
								memcpy(&temp,res.value.data,8);
								variables[i].data = (void *)temp;

								variables[i].type=res.value.type->typeId.identifier.numeric;

							}
							else if(NodeAddInfos[i].AttributeID == UA_ATTRIBUTEID_NODECLASS)
							{
								//UA_NodeClass *out1;
								//memcpy(out1, (UA_NodeClass*)res.value.data, sizeof(UA_NodeClass));
								memcpy(variables[i].data,res.value.data,8);
								variables[i].type=UA_TYPES_NODECLASS;
							}
							else if(UA_Variant_isScalar(&res.value))
							{
								//memcpy(&variables[i].data, &res.value.data, res.value.type->memSize);
								//UA_free(res.value.data);
								//res.value.data = 0;
								variables[i].type=res.value.type->typeId.identifier.numeric;
							}
							else
							{
								retval = UA_STATUSCODE_BADUNEXPECTEDERROR;
							}

						}
						UA_free(res.value.data);   //?????   need or not
					}
                }  //end for
            }
            else
            {

                retval = UA_STATUSCODE_BADUNEXPECTEDERROR;
            }
        }//end if(retval == UA_STATUSCODE_GOOD)
      //  printf("------------#f8 --------------\n");
        // UA_ReadResponse_clear(&response);
    }

    return retval;
}

u32 UA_WriteList(long ConnectionHdl,u16 NodeHdlCount,long *NodeHdls,UANodeAdditionalInfo *NodeAddInfos,UA_Value *variables,u32 ErrorIDs[]){
	UA_Client *c = (UA_Client*)ConnectionHdl;
	int i;
	UA_StatusCode retval=0;
	if(NodeHdlCount>MAX_ELEMENTS_NODELIST){
		retval=0xA0000002;
		return retval;
	}
	//UA_NodeId NODEid= UA_NODEID_STRING(1, "A1.the anwser2");
	//UA_Client_writeValueAttribute(c,NODEid,&in);
	UA_WriteValue wValue[NodeHdlCount];
	for(i=0;i<NodeHdlCount;i++){
		UA_WriteValue_init(&wValue[i]);
	 	wValue[i].nodeId = *(UA_NodeId*)NodeHdls[i];
	 	//wValue[i].nodeId = NODEid;
	 	wValue[i].attributeId = NodeAddInfos[i].AttributeID;
	 	if(NodeAddInfos[i].AttributeID == UA_ATTRIBUTEID_VALUE){
	 		UA_Variant in;
			UA_Variant_init(&in);
			UA_Variant_setScalar(&in,variables[i].data,&UA_TYPES[variables[i].type-1]);
         	wValue[i].value.value = in;
			wValue[i].value.hasValue = true;
	 	}
	 	else{
	 		UA_Variant_setScalar(&wValue[i].value.value, (void*)(uintptr_t)variables[i].data, &UA_TYPES[variables[i].type-1]);
		}
	}
	UA_WriteRequest wReq;
	UA_WriteRequest_init(&wReq);
	wReq.nodesToWrite = &wValue[0];
	wReq.nodesToWriteSize = NodeHdlCount;

	UA_WriteResponse wResp = UA_Client_Service_write(c, wReq);

	retval = wResp.responseHeader.serviceResult;
	if(retval==UA_STATUSCODE_GOOD){
		if(wResp.resultsSize==NodeHdlCount){
			for(i=0;i<NodeHdlCount;i++){
				ErrorIDs[i]=wResp.results[i];
			}
		}else{
			retval=UA_STATUSCODE_BADUNEXPECTEDERROR;
		}
	}
	UA_WriteRequest_clear(&wResp);
	return retval;
}

void readTest(long ConnectionHdl,u16 NodeHdlCount,long *NodeHdls,UA_Value *variables,u32 ErrorIDs[])
{
    UA_Client *c = (UA_Client*)ConnectionHdl;
	int i;
	u32 retval;
 	UA_ReadValueId item[NodeHdlCount];
	if(NodeHdlCount>MAX_ELEMENTS_NODELIST){
		retval=0xA0000002;
	}
	else
    {
        for(i=0;i<NodeHdlCount;i++){
            UA_ReadValueId_init(&item[i]);
            item[i].nodeId = *(UA_NodeId*)NodeHdls[i];
            //item[i].nodeId.identifier.numeric = NodeHdls[i];//zjy 20240910
            item[i].attributeId = 1;
            //item[i].nodeId.namespaceIndex = 1;
            printf("------------#2------NodeHdls[i] = %ld ,item[i].nodeId = %d,item[i].attributeId=%d,item[i].nodeId.namespaceIndex=%d-\n",
               NodeHdls[i],item[i].nodeId.identifier.string.length,item[i].attributeId,item[i].nodeId.namespaceIndex);
        }
        UA_ReadRequest request;
        UA_ReadRequest_init(&request);
        request.nodesToRead = &item[0];
        request.nodesToReadSize = 1;
        UA_ReadResponse response = UA_Client_Service_read(c, request);
        retval = response.responseHeader.serviceResult;
        if(retval == UA_STATUSCODE_GOOD)
        {
            printf("------------#3---------------\n");
            printf("%d\n",response.resultsSize);
            if(response.resultsSize==NodeHdlCount)
            {
                printf("------------#4---------------\n");
                for (i = 0; i < NodeHdlCount; i++)
                {
                    ErrorIDs[i]=response.results[i].status;
                }
                retval = 0 ;
                for(i=0;i<NodeHdlCount;i++)
                {
                    if(ErrorIDs[i]==UA_STATUSCODE_GOOD)
                    {
                        printf("------------#5---------------\n");
                        UA_DataValue res = response.results[i];
                        if(!res.hasValue)
                        {
                            printf("------------#6---------------\n");
                            UA_ReadResponse_clear(&response);
                            retval =  UA_STATUSCODE_BADUNEXPECTEDERROR;
                        }
						else
						{
  							memcpy(variables[i].data,res.value.data,8);
							variables[i].type=UA_TYPES_NODECLASS;
						}
						UA_free(res.value.data);   //?????   need or not
					}
                }  //end for
            }
            else
            {

                retval = UA_STATUSCODE_BADUNEXPECTEDERROR;
            }
        }
    }
}

void writeTest(long ConnectionHdl,u16 NodeHdlCount,long *NodeHdls,UA_Value *variables,u32 ErrorIDs[]){
    UA_Client *c = (UA_Client*)ConnectionHdl;
	int i;
	UA_StatusCode retval=0;
	if(NodeHdlCount>MAX_ELEMENTS_NODELIST){
		retval=0xA0000002;
		return retval;
	}
	//UA_NodeId NODEid= UA_NODEID_STRING(1, "A1.the anwser2");
	//UA_Client_writeValueAttribute(c,NODEid,&in);
	UA_WriteValue wValue[NodeHdlCount];
	for(i=0;i<NodeHdlCount;i++){
		UA_WriteValue_init(&wValue[i]);
	 	wValue[i].nodeId = *(UA_NodeId*)NodeHdls[i];
	 	//wValue[i].nodeId = NODEid;
	 	wValue[i].attributeId = 1;
	 	UA_Variant_setScalar(&wValue[i].value.value, (void*)(uintptr_t)variables[i].data, &UA_TYPES[variables[i].type-1]);
	}
	UA_WriteRequest wReq;
	UA_WriteRequest_init(&wReq);
	wReq.nodesToWrite = &wValue[0];
	wReq.nodesToWriteSize = NodeHdlCount;

	UA_WriteResponse wResp = UA_Client_Service_write(c, wReq);

	retval = wResp.responseHeader.serviceResult;
	if(retval==UA_STATUSCODE_GOOD){
		if(wResp.resultsSize==NodeHdlCount){
			for(i=0;i<NodeHdlCount;i++){
				ErrorIDs[i]=wResp.results[i];
			}
		}else{
			retval=UA_STATUSCODE_BADUNEXPECTEDERROR;
		}
	}
	UA_WriteRequest_clear(&wResp);
	return retval;
}

u32 SubscriptionCreate(long ConnectionHdl,bool PublishingEnable,u16 Priority,long *SubscriptionHdl,TIME *PublishingInterval){
	UA_Client *c = (UA_Client*)ConnectionHdl;
	UA_CreateSubscriptionRequest request = UA_CreateSubscriptionRequest_default();
	request.requestedPublishingInterval=*PublishingInterval;
	request.publishingEnabled=PublishingEnable;
	request.priority=Priority;
	UA_CreateSubscriptionResponse *response=malloc(sizeof(UA_CreateSubscriptionResponse));
	*response = UA_Client_Subscriptions_create(c,request,NULL,NULL,NULL);
	u32 retval=response[0].responseHeader.serviceResult;
	if(retval!=UA_STATUSCODE_GOOD){
		UA_CreateSubscriptionResponse_clear(&response[0]);
		return retval;
	}
	printf("response[0].subscripstionId is %x\n",response[0].subscriptionId);
	*SubscriptionHdl=(long *)response[0].subscriptionId;
	UA_CreateSubscriptionResponse_clear(&response[0]);
	return retval;
}

u32 UA_SubscriptionDelete(long ConnectionHdl,long SubscriptionHdl){
	UA_Client *c = (UA_Client*)ConnectionHdl;
	u32 retval=UA_Client_Subscriptions_deleteSingle(c,SubscriptionHdl);
	return retval;
}

u32 SubscriptionHdlzu2[100];
u32 MonItemHdlzu[100];
UAMonitoredVariables MonVlaue[100];
int MontNum=0;
static void handler_DataChanged(UA_Client *client, UA_UInt32 subId,
                                    void *subContext, UA_UInt32 monId,
                                    void *monContext, UA_DataValue *value)
{
    UA_LOG_INFO(UA_Log_Stdout, UA_LOGCATEGORY_CLIENT, "Received Notification");

    UA_NodeId *ptr = (UA_NodeId*)monContext;
	SubscriptionHdlzu2[MontNum]=subId;
	MonItemHdlzu[MontNum]=monId;
	MonVlaue[MontNum].Values.data=value->value.data;
	MonVlaue[MontNum].Values.type=value->value.type->typeId.identifier.numeric;
	UA_DateTime now = UA_DateTime_nowMonotonic();
	MonVlaue[MontNum].TimeStamps=now;
	MonVlaue[MontNum].NewValuesCount=1;
	//MonVlaue[MontNum].NodeQualityIDs[0]=0;
    //UA_Int32 currentValue = *(UA_Int32*)(value->value.data);

	MontNum++;
}

u32 MonitoredItemAddList(long ConnectionHdl,long SubscriptionHdl,u16 NodeHdlCount,
							long *NodeHdls,UAMonitoringSyncMode SyncMode,
							UANodeAdditionalInfo *NodeAddInfos,u32 *MonitoredItemHdls,u32 ErrorIDs[]){
	UA_Client *c = (UA_Client*)ConnectionHdl;
	u32 retval=0;
	if(NodeHdlCount>MAX_ELEMENTS_MONITORLIST){
		retval=0xA0000002;
		return retval;
	}
	if(SyncMode==UAMS_ControllerSync){
		for(int i=0;i<NodeHdlCount;i++){
			UA_NodeId *NodeID=(UA_NodeId*)NodeHdls[i];
			UA_MonitoredItemCreateRequest monRequest=UA_MonitoredItemCreateRequest_default(*NodeID);
			monRequest.itemToMonitor.attributeId = NodeAddInfos[i].AttributeID;
			UA_MonitoredItemCreateResult monResponse=
			UA_Client_MonitoredItems_createDataChange(c,SubscriptionHdl,UA_TIMESTAMPSTORETURN_BOTH,
														monRequest,NodeID,handler_DataChanged,NULL);
		if(monResponse.statusCode!=UA_STATUSCODE_GOOD){
			retval=monResponse.statusCode;
		}
		ErrorIDs[i]=monResponse.statusCode;
		MonitoredItemHdls[i]=monResponse.monitoredItemId;
		}
	}
	return retval;

}

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("\n%lld\n\n",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, 64, "%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(hdl,4,nodes,nodeHdls,errors);
    UA_Value *variables = (UA_Value*)malloc(4 * sizeof(UA_Value));
	readTest(hdl,4,nodeHdls,variables,errors);
    for (int i = 0; i < 4; i++)
    {
        printf("%d\n",variables[i].type);
    }
    

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