#include "stddef.h"
#include <string.h>
#include <stdio.h>
#include "kk_tsl_common.h"
#include "kk_dm_mng.h"

#ifndef _ZLOG_
#undef      INFO_PRINT
#undef      WARNING_PRINT
#undef      ERROR_PRINT

#define    INFO_PRINT      printf
#define    WARNING_PRINT   printf
#define    ERROR_PRINT     printf
#else
#include "kk_log.h"
#endif


#define TSL_SUBDEVICE_PATH_FILE "/home/kk/tsl/product_%s.json"
#define TSL_GATEWAY_PATH_FILE "/home/kk/tsl/gateway-%s.json"
#define TSL_CCU_PATH_FILE "/home/kk/tsl/ccu-%s.json"

char* kk_load_json(const char *productCode,int type)
{
	FILE *fp;
	char *buf = NULL;
	char *tslPath = NULL;
	int path_len = 0;
	unsigned int filesize;

	if(type == KK_DM_DEVICE_CCU){
		path_len = strlen(TSL_CCU_PATH_FILE)+strlen(productCode)+1;
	}
	else if(type == KK_DM_DEVICE_GATEWAY){
		path_len = strlen(TSL_GATEWAY_PATH_FILE)+strlen(productCode)+1;
	}
	else{
		path_len = strlen(TSL_SUBDEVICE_PATH_FILE)+strlen(productCode)+1;
	}

	tslPath = malloc(path_len);
	if(tslPath == NULL){
		return NULL;
	}
	memset(tslPath,0x0,path_len);
	
	if(type == KK_DM_DEVICE_CCU){
		snprintf(tslPath,path_len,TSL_CCU_PATH_FILE,productCode);
	}
	else if(type == KK_DM_DEVICE_GATEWAY){
		snprintf(tslPath,path_len,TSL_GATEWAY_PATH_FILE,productCode);
	}
	else{
		snprintf(tslPath,path_len,TSL_SUBDEVICE_PATH_FILE,productCode);
	}
	
	
	INFO_PRINT("\n[%s][%d]tslPath:%s!!!\n",__FUNCTION__,__LINE__,tslPath);
	if(!(fp =  fopen(tslPath,"a+")))
	{
		ERROR_PRINT("can't open the file tslPath:%s\n",tslPath);
		free(tslPath);
		return NULL;
	}
    fseek(fp, 0L, SEEK_END);
    filesize = ftell(fp);	
	buf = malloc(filesize+1);
	if(buf == NULL)
	{
		ERROR_PRINT("MALLOC FAIL!!!\n");
		free(tslPath);
		return NULL;

	}
	memset(buf,0x0,filesize+1);
	fseek(fp, 0L, SEEK_SET);
	fread(buf, 1, filesize, fp);
	//printf("%s!!!\n",buf);	
	free(tslPath);
	fclose(fp);
	return buf;
}

