
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "kk_product.h"
#include "cJSON.h"

const char KK_URI_SYS_PREFIX[] = "/sys/%s/%s/#";

int KK_Subdev_Subscribe(const cJSON *root)
{
	int res = 0;		
	cJSON *productType = NULL;
	cJSON *productCode = NULL;
	cJSON *data	= NULL;
	cJSON *cmd = NULL;	
    int url_len = 0;	
	
	data = cJSON_GetObjectItem(root, "data");
	if(data == NULL){
		return -1;
	}
	productType = cJSON_GetObjectItem(data,"productType");
	if(productType == NULL){
		return -1;
	}
	productCode = cJSON_GetObjectItem(data,"productCode");
	if(productCode == NULL){
		return -1;
	}	
    url_len = strlen(KK_URI_SYS_PREFIX) + strlen(productType->valuestring) + strlen(productCode->valuestring) + 1;
    char  *url = malloc(url_len);
    if (url == NULL) {
        return -1;
    }
    memset(url, 0, url_len);
    snprintf(url, url_len, KK_URI_SYS_PREFIX, productType->valuestring, productCode->valuestring);
    printf("[%s][%d] URL:%s\n",__FUNCTION__,__LINE__,url);
    res = KK_MQTT_SubTopic(url);
    free(url);
	return res;

}

static int _kk_client_subscribe(char productType[PRODUCT_TYPE_LEN], char productCode[PRODUCT_CODE_LEN])
{
    int res = 0, index = 0, fail_count = 0;

    int url_len = 0;
	printf("[%s][%d] \n",__FUNCTION__,__LINE__);
    url_len = strlen(KK_URI_SYS_PREFIX) + strlen(productType) + strlen(productCode) + 1;
    char  *url = malloc(url_len);
    if (url == NULL) {
        return -1;
    }
    memset(url, 0, url_len);

    snprintf(url, url_len, KK_URI_SYS_PREFIX, productType, productCode);
    printf("[%s][%d] URL:%s\n",__FUNCTION__,__LINE__,url);

    res = KK_MQTT_SubTopic(url);

    free(url);
    return res;
}

int KK_Client_Gateway_Subscribe(void)
{
	char prpductType[PRODUCT_TYPE_LEN];
	char prpductCode[PRODUCT_CODE_LEN];

	HAL_GetProduct_Type(prpductType);
	HAL_GetProduct_Code(prpductCode);
	return _kk_client_subscribe(prpductType,prpductCode);
}



