#include "stddef.h"
#include <string.h>
#include <stdio.h>
#include "kk_tsl_common.h"
#include "kk_dm_mng.h"
#include "kk_log.h"
#define TSL_SUBDEVICE_PATH_FILE "/usr/kk/tsl/product_%s.json"
#define TSL_GATEWAY_PATH_FILE "/usr/kk/tsl/gateway_%s.json"
#define TSL_CCU_PATH_FILE "/usr/kk/tsl/ccu_%s.json"
#define TSL_SCENE_PATH_FILE "/usr/kk/tsl/ccu_%s_scene.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 if(type == KK_DM_DEVICE_SUBDEV){
		path_len = strlen(TSL_SUBDEVICE_PATH_FILE)+strlen(productCode)+1;
	}
	else{
		path_len = strlen(TSL_SCENE_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 if(type == KK_DM_DEVICE_SUBDEV){
		snprintf(tslPath,path_len,TSL_SUBDEVICE_PATH_FILE,productCode);
	}
	else{
		snprintf(tslPath,path_len,TSL_SCENE_PATH_FILE,productCode);
	}
	
	
	INFO_PRINT("\n[%s][%d]tslPath:%s!!!\n",__FUNCTION__,__LINE__,tslPath);
	if(!(fp =  fopen(tslPath,"r")))
	{
		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;
}

