#include "kk_tsl_property_set.h"

static uint8_t s_Red = 0xff;
static uint8_t s_Green = 0xff;
static uint8_t s_Blue = 0xff;
static uint8_t s_RgbCount = 0;

//emberAfAppPrintln("[tsl report:Gloabl] OnOff~~~~~~~~~");

//cJSON *rpc_Control(jrpc_context * ctx, cJSON *params, cJSON *id,cJSON *mac)
cJSON *kk_topo_change_operation(jrpc_context * ctx, cJSON *params, cJSON *id,cJSON *mac)
{
	int res = 0;
    cJSON *changeTypeStr = NULL;
	uint8_t eui64[EUI64_SIZE] = {0};
	EmberNodeId nodeId = EMBER_AF_PLUGIN_DEVICE_TABLE_NULL_NODE_ID;

	UTIL_LOG_INFO("\n********************kk_topo_change_operation********************\n");

	if(params == NULL){
		set_json_error_type(ctx,JRPC_INVALID_PARAMS,MSG_INVALID_PARAMS);
		goto error_return;
	}else{
		changeTypeStr = rpc_cJSON_GetObjectItem(params, MSG_TOPO_CHANGE_TYPE_STR);
		if(changeTypeStr != NULL && changeTypeStr->valueint == 1){
		    cJSON *deviceArray = rpc_cJSON_GetObjectItem(params, MSG_TOPO_CHANGE_DEVICES_STR);
		    if(deviceArray == NULL){
			   goto error_return;
		    }			
			cJSON * item = deviceArray->child;
			while(item != NULL){
				char *deviceCode = rpc_cJSON_GetObjectItem(item,MSG_DEVICE_CODE_STR)->valuestring;
				rpc_get_mac(deviceCode,eui64);
				nodeId = emberAfDeviceTableGetNodeIdFromEui64(eui64);
				kk_zdo_leave_request(nodeId,false,false);
				item = item->next;
			}

		}


	}
	return rpc_cJSON_CreateNumber(res);
error_return:
	return rpc_cJSON_CreateNull();
}
int kk_tsl_utils_memtok(_IN_ char *input, _IN_ char *delimiter, _IN_ int index, _OU_ int *offset)
{
    int item_index = 0;
    int count = 0;
	int input_len = 0;

    if (input == NULL || offset == NULL) {
        return -1;
    }
	input_len = strlen(input);
    for (item_index = 0; item_index < input_len; item_index++) {
        if (input[item_index] == delimiter && (item_index + 1) < input_len) {
            count++;
            if (count == index) {
                *offset = item_index;
                return 0;
            }
        }
    }

    return -1;
}
static int kk_tsl_property_execute(jrpc_context * ctx,cJSON * propertyItem,cJSON *mac,int index,int findFlag)
{
	int value = 0;
	EmberEUI64 eui64;
	EmberNodeId nodeId = EMBER_AF_PLUGIN_DEVICE_TABLE_NULL_NODE_ID;
	int res = 0;

	if(propertyItem == NULL || mac == NULL){
		return -1;
	}
	if(propertyItem->type != cJSON_Number){
		value = rpc_get_u8(propertyItem->valuestring);
	}else{
		value = propertyItem->valueint;
	}	
	if(rpc_get_mac(mac->valuestring,eui64)==false){
		return -1;
	}	
	printf("[%s][%d]g_tsl_zigbee_map[index].endpoint:%d\n",__FUNCTION__,__LINE__,g_tsl_zigbee_map[index].endpoint);
	nodeId = emberAfDeviceTableGetNodeIdFromEui64(eui64);	
	if(findFlag==1)
		res = g_tsl_zigbee_map[index].zigbee_set(ctx,nodeId,g_tsl_zigbee_map[index].endpoint,&value);
	else if(findFlag==2)
		res = g_tsl_zigbee_map_glb[index].map.zigbee_set(ctx,nodeId,g_tsl_zigbee_map_glb[index].map.endpoint,&value);
	else
		res = -1;
	printf("[%s][%d]res:%d\n",__FUNCTION__,__LINE__,res);
	return res;
			
}
cJSON *kk_tsl_property_operation(jrpc_context * ctx, cJSON *params, cJSON *id,cJSON *mac)
{
    sub_dev_node_t *node = NULL;
	int res = 0,rev = 0;
	rpc_nwk_info_s info;
	EmberStatus status;
	int index = 0;
	zigbee_property_set *func;
	int num;
	uint8_t findFlag = 0xff;
    cJSON *propertyItem = NULL;
	cJSON *propertyItem1 = NULL;
	int startIdx_1 = 0;
	cJSON *propertyItem2 = NULL;	
	int startIdx = 0;
	char tmp_Identity[64] = {0};	
	UTIL_LOG_INFO("\n********************kk tsl property operation********************\n");

	if(params == NULL){
		set_json_error_type(ctx,JRPC_INVALID_PARAMS,MSG_INVALID_PARAMS);
		goto error_return;
	}else{
		res = kk_sub_tsl_get_device_by_mac(mac->valuestring, &node);
		if (res != SUCCESS_RETURN) {
			printf("[%s][%d]\n",__FUNCTION__,__LINE__);
			set_json_error_type(ctx,JRPC_INVALID_PARAMS,MSG_INVALID_PARAMS);
			goto error_return;
		}
		
		num = kk_get_tsl_num();
		for(index = 0; index < num; index++){	
			
			rev = kk_tsl_utils_memtok(g_tsl_zigbee_map[index].Identity,'.',2,&startIdx);
			if(!rev){
				kk_tsl_utils_memtok(g_tsl_zigbee_map[index].Identity,'.',1,&startIdx_1);
				memset(tmp_Identity,0x0,sizeof(tmp_Identity));
				memcpy(tmp_Identity, g_tsl_zigbee_map[index].Identity, startIdx_1);
				propertyItem2 = rpc_cJSON_GetObjectItem(params,tmp_Identity);
				if(propertyItem2 != NULL){
					memset(tmp_Identity,0x0,sizeof(tmp_Identity));
					memcpy(tmp_Identity, g_tsl_zigbee_map[index].Identity+startIdx_1+1, startIdx-startIdx_1);
					propertyItem1 = rpc_cJSON_GetObjectItem(propertyItem2,tmp_Identity);
					if(propertyItem1 != NULL){
						propertyItem = rpc_cJSON_GetObjectItem(propertyItem1,g_tsl_zigbee_map[index].Identity+startIdx+1);
						if(propertyItem != NULL){
							findFlag = 1;
						}
						//break;

					}
				}

			}
			else{
				rev = kk_tsl_utils_memtok(g_tsl_zigbee_map[index].Identity,'.',1,&startIdx);
				if(!rev){
					memset(tmp_Identity,0x0,sizeof(tmp_Identity));
					memcpy(tmp_Identity, g_tsl_zigbee_map[index].Identity, startIdx);
					propertyItem1 = rpc_cJSON_GetObjectItem(params,tmp_Identity);
					if(propertyItem1 != NULL){
						propertyItem = rpc_cJSON_GetObjectItem(propertyItem1,g_tsl_zigbee_map[index].Identity+startIdx+1);
						if(propertyItem != NULL){
							findFlag = 1;
							//break;

						}
					}

				}
				else{
					propertyItem = rpc_cJSON_GetObjectItem(params, g_tsl_zigbee_map[index].Identity);
					if(propertyItem != NULL){
						findFlag = 1;
						//break;
					}
				}
			}
			if(findFlag == 1){
				res = kk_tsl_property_execute(ctx,propertyItem,mac,index,findFlag);
				if(res < 0){
					set_json_error_type(ctx,JRPC_INVALID_PARAMS,MSG_INVALID_PARAMS);
					goto error_return;
				}
				else{
					findFlag = 0;
				}
			}
		}
		if(findFlag==0xff){
			num = kk_get_tsl_glb_num();
			for(index = 0; index < num; index++){
				rev = kk_tsl_utils_memtok(g_tsl_zigbee_map_glb[index].map.Identity,'.',2,&startIdx);
				if(!rev){
					kk_tsl_utils_memtok(g_tsl_zigbee_map_glb[index].map.Identity,'.',1,&startIdx_1);					
					memset(tmp_Identity,0x0,sizeof(tmp_Identity));
					memcpy(tmp_Identity, g_tsl_zigbee_map_glb[index].map.Identity, startIdx_1);
					propertyItem2 = rpc_cJSON_GetObjectItem(params,tmp_Identity);
					if(propertyItem2!= NULL){
						memset(tmp_Identity,0x0,sizeof(tmp_Identity));
						memcpy(tmp_Identity, g_tsl_zigbee_map_glb[index].map.Identity+startIdx_1+1, startIdx-startIdx_1);
						propertyItem1 = rpc_cJSON_GetObjectItem(propertyItem2,tmp_Identity);
						if(propertyItem1 != NULL){
							propertyItem = rpc_cJSON_GetObjectItem(propertyItem1,g_tsl_zigbee_map_glb[index].map.Identity+startIdx+1);
							if(propertyItem != NULL){
								findFlag = 2;
							}
						}
					}

				}	
				else{	
					rev = kk_tsl_utils_memtok(g_tsl_zigbee_map_glb[index].map.Identity,'.',1,&startIdx);
					if(!rev){
						memset(tmp_Identity,0x0,sizeof(tmp_Identity));
						memcpy(tmp_Identity, g_tsl_zigbee_map_glb[index].map.Identity, startIdx);
						propertyItem1 = rpc_cJSON_GetObjectItem(params,tmp_Identity);
						if(propertyItem1 != NULL){
							propertyItem = rpc_cJSON_GetObjectItem(propertyItem1,g_tsl_zigbee_map_glb[index].map.Identity+startIdx+1);
							if(propertyItem != NULL){
								findFlag = 2;
					
							}
						}
					
					}
					else{
						propertyItem = rpc_cJSON_GetObjectItem(params, g_tsl_zigbee_map_glb[index].map.Identity);
						if(propertyItem != NULL){
							findFlag = 2;
						}
					}
				}
				if(findFlag == 2){
					res = kk_tsl_property_execute(ctx,propertyItem,mac,index,findFlag);
					if(res < 0){
						set_json_error_type(ctx,JRPC_INVALID_PARAMS,MSG_INVALID_PARAMS);
						goto error_return;
					}
					else{
						findFlag = 0;
					}
				}
			}
		}
		return rpc_cJSON_CreateNumber(res);					
	}
error_return:
	return rpc_cJSON_CreateNull();
}

int kk_tsl_set_colorlight_ModeType(jrpc_context * ctx,EmberNodeId node,unsigned char ep,void* data)
{
	int value = *(uint8_t*)data;
	emberAfAppPrintln("[tsl set:kk_tsl_set_colorloght_ModeType],value=0x%02x",value);
	return 0;
}

int kk_tsl_set_colorlight_Mode(jrpc_context * ctx,EmberNodeId node,unsigned char ep,void* data)
{
	EmberStatus status = 0; 

	int value = *(uint8_t*)data;
	emberAfAppPrintln("[tsl set:kk_tsl_set_colorloght_Mode],value=0x%02x",value);
	if(node==EMBER_AF_PLUGIN_DEVICE_TABLE_NULL_NODE_ID){
		if(ctx)
			set_json_error_type(ctx,JRPC_INVALID_PARAMS,MSG_INVALID_PARAMS);
		goto error_return;
	}	
	status = zclColorControlLoopSet(node,ep,value,0,0,1,55,0,0,0);
	return status;
error_return:
	return -1;	
}

int kk_tsl_set_colorlight_Brightness(jrpc_context * ctx,EmberNodeId node,unsigned char ep,void* data)
{
	int value = *(uint8_t*)data;
	EmberStatus status = 0;	
	emberAfAppPrintln("[tsl set:kk_tsl_set_colorloght_Brightness],value=0x%02x",value);
	if(node==EMBER_AF_PLUGIN_DEVICE_TABLE_NULL_NODE_ID){
		if(ctx)
			set_json_error_type(ctx,JRPC_INVALID_PARAMS,MSG_INVALID_PARAMS);
		goto error_return;
	}	
	#if 0
	printf("[%s][%d]\n",__FUNCTION__,__LINE__);
	value |= BIT(1);
	printf("[%s][%d]\n",__FUNCTION__,__LINE__);
	status = zclGWrite(node,1,ep,false,0x08,
				0,
				ZCL_BITMAP8_ATTRIBUTE_TYPE,
				1,
				value,
				true);
	emberAfAppPrintln("status=0x%02x",status);
	#else
	status = zclLevel_MoveToLevel(node,ep,value,0,NULL,NULL);

	#endif
	return status;	
error_return:
	return -1;		
}
int kk_tsl_set_colorlight_WhiteBrightness(jrpc_context * ctx,EmberNodeId node,unsigned char ep,void* data)
{
	int value = *(uint8_t*)data;
	emberAfAppPrintln("[tsl set:kk_tsl_set_colorloght_WhiteBrightness],value=0x%02x",value);
	return 0;
}

int kk_tsl_set_colorlight_RGB_red(jrpc_context * ctx,EmberNodeId node,unsigned char ep,void* data)
{
	int value = *(uint8_t*)data;
	EmberStatus status = 0;
	emberAfAppPrintln("[tsl set:kk_tsl_set_colorloght_RGB_red],value=0x%02x",value);
	s_Red  = value;
	s_RgbCount++;
	if(s_RgbCount >= 3){
		status = zclColorControlMovetohueandsat(node,ep,s_Red,s_Green,s_Blue,0,0,0);
		s_RgbCount = 0;
	}
	return status;
}
int kk_tsl_set_colorlight_RGB_green(jrpc_context * ctx,EmberNodeId node,unsigned char ep,void* data)
{
	int value = *(uint8_t*)data;
	EmberStatus status = 0;	
	emberAfAppPrintln("[tsl set:kk_tsl_set_colorloght_RGB_green],value=0x%02x",value);
	s_Green  = value;
	s_RgbCount++;
	if(s_RgbCount >= 3){
		status = zclColorControlMovetohueandsat(node,ep,s_Red,s_Green,s_Blue,0,0,0);
		s_RgbCount = 0;
	}

	return status;
}
int kk_tsl_set_colorlight_RGB_blue(jrpc_context * ctx,EmberNodeId node,unsigned char ep,void* data)
{
	int value = *(uint8_t*)data;
	EmberStatus status = 0;	
	emberAfAppPrintln("[tsl set:kk_tsl_set_colorloght_RGB_blue],value=0x%02x",value);
	s_Blue  = value;
	s_RgbCount++;
	if(s_RgbCount >= 3){
		status = zclColorControlMovetohueandsat(node,ep,s_Red,s_Green,s_Blue,0,0,0);
		s_RgbCount = 0;
	}

	return status;
}


int kk_tsl_set_colorlight_OnOff(jrpc_context * ctx,EmberNodeId node,unsigned char ep,void* data)
{
	uint8_t Onoff	= 0;
	EmberStatus status = 0;

	Onoff = *(uint8_t*)data;
	emberAfAppPrintln("[tsl set:OnOff],Onoff=0x%02x",Onoff);

	if(node==EMBER_AF_PLUGIN_DEVICE_TABLE_NULL_NODE_ID){
		if(ctx)
			set_json_error_type(ctx,JRPC_INVALID_PARAMS,MSG_INVALID_PARAMS);
		goto error_return;
	}
	
	if(Onoff==1){
		//status = zclGWrite(node,1,1,false,0xFCC0,0,ZCL_BITMAP8_ATTRIBUTE_TYPE,1,Onoff,true);
		status = zclOnOff_On(node,ep);
		emberAfAppPrintln("On");
	}else if(Onoff==0){
		//status = zclGWrite(node,1,1,false,0xFCC0,0,ZCL_BITMAP8_ATTRIBUTE_TYPE,1,Onoff,true);
		status = zclOnOff_Off(node,ep);
		emberAfAppPrintln("Off");
	}else{
		if(ctx)
			set_json_error_type(ctx,JRPC_INVALID_PARAMS,MSG_INVALID_PARAMS);
		goto error_return;
	}

	emberAfAppPrintln("status=0x%02x",status);
	return status;
error_return:
	return -1;

}

int kk_tsl_set_gloabl_OnOff(jrpc_context * ctx,EmberNodeId node,unsigned char ep,void* data)
{
	uint8_t Onoff	= 0;
	EmberStatus status = 0;

	Onoff = *(uint8_t*)data;
	emberAfAppPrintln("[tsl set:OnOff],Onoff=0x%02x",Onoff);

	if(node==EMBER_AF_PLUGIN_DEVICE_TABLE_NULL_NODE_ID){
		if(ctx)
			set_json_error_type(ctx,JRPC_INVALID_PARAMS,MSG_INVALID_PARAMS);
		goto error_return;
	}
	
	if(Onoff==1){
		status = zclOnOff_On(node,ep);
		emberAfAppPrintln("On");
	}else if(Onoff==0){
		status = zclOnOff_Off(node,ep);
		emberAfAppPrintln("Off");
	}else{
		if(ctx)
			set_json_error_type(ctx,JRPC_INVALID_PARAMS,MSG_INVALID_PARAMS);
		goto error_return;
	}

	emberAfAppPrintln("status=0x%02x",status);
	return status;
error_return:
	return -1;

}


int kk_tsl_set_windowCovering_OperationMode(jrpc_context * ctx,EmberNodeId node,unsigned char ep,void* data)
{
	uint8_t Operation	= 0;
	EmberStatus status = 0;

	Operation = *(uint8_t*)data;
	emberAfAppPrintln("[tsl set:Window Covering Operation Mode],mode=0x%02x",Operation);

	if(node==EMBER_AF_PLUGIN_DEVICE_TABLE_NULL_NODE_ID){
		if(ctx)
			set_json_error_type(ctx,JRPC_INVALID_PARAMS,MSG_INVALID_PARAMS);
		goto error_return;
	}
	
	if(Operation==0){
		status = WindowCover_UpOpen(node,ep);
		emberAfAppPrintln("Up/Open");
	}else if(Operation==1){
		status = WindowCover_DownClose(node,ep);
		emberAfAppPrintln("Down/Close");
	}else if(Operation==2){
		status = WindowCover_Stop(node,ep);
		emberAfAppPrintln("Stop");
	}else{
		if(ctx)
			set_json_error_type(ctx,JRPC_INVALID_PARAMS,MSG_INVALID_PARAMS);
		goto error_return;
	}

	emberAfAppPrintln("status=0x%02x",status);
	return status;
error_return:
	return -1;
}

int kk_tsl_set_windowCovering_mode(jrpc_context * ctx,EmberNodeId node,unsigned char ep,void* data)
{
	uint8_t mode	= 0;
	uint8_t WCmode	= 0;
	EmberStatus status = 0;

	mode = *(uint8_t*)data;
	emberAfAppPrintln("[tsl set:Window Covering Run Mode],mode=0x%02x",mode);

	if(mode==WC_calibration_mode){
		WCmode |= BIT(1);
	
		status = zclGWrite(node,1,ep,false,ZCL_WINDOW_COVERING_CLUSTER_ID,
					ZCL_MODE_ATTRIBUTE_ID,
					ZCL_BITMAP8_ATTRIBUTE_TYPE,
					1,
					WCmode,
					true);
		emberAfAppPrintln("Calibration Mode");
	}else if(mode==WC_reversed_dir){
		WCmode |= BIT(0);
		status = zclGWrite(node,1,ep,false,ZCL_WINDOW_COVERING_CLUSTER_ID,
							ZCL_MODE_ATTRIBUTE_ID,
							ZCL_BITMAP8_ATTRIBUTE_TYPE,
							1,
							WCmode,
							true);
		emberAfAppPrintln("Dir:reversed");
	}else if(mode==WC_normal_dir){
		WCmode = 0;
		status = zclGWrite(node,1,ep,false,ZCL_WINDOW_COVERING_CLUSTER_ID,
						ZCL_MODE_ATTRIBUTE_ID,
						ZCL_BITMAP8_ATTRIBUTE_TYPE,
						1,
						WCmode,
						true);
		emberAfAppPrintln("Dir:Normal");
	}else{
		if(ctx)
			set_json_error_type(ctx,JRPC_INVALID_PARAMS,MSG_INVALID_PARAMS);
		goto error_return;
	}
	emberAfAppPrintln("status=0x%02x",status);
	return status;
error_return:
	return -1;
}
int kk_tsl_set_windowCovering_position(jrpc_context * ctx,EmberNodeId node,unsigned char ep,void* data)
{
	uint8_t position	= 0;
	EmberStatus status = 0;

	position = *(uint8_t*)data;
	emberAfAppPrintln("[tsl set:Window Covering Position],position=0x%02x",position);

	status = WindowCover_GotoLiftPercentage(node,ep,position);

	emberAfAppPrintln("status=0x%02x",status);
	return status;
error_return:
	return -1;
}






















