#include <stdio.h>
#include <stdlib.h>
#include <string.h>


#include "kk_data_mng.h"
#include "kk_ccu_msg.h"
#include "kk_lan_sync.h"
#include "kk_lan_debug.h"
#include "kk_lan_node_db.h"
#include "kk_lan_new_dev_notify.h"


/*******获取同步数据json*******/
static cJSON *kk_get_sync_data(cJSON *payload)
{
	return cJSON_GetObjectItem(payload,DATA_STR);
}


/*******同步信息-同步房间*******/
static cJSON *_kk_syn_room_item(SYN_ROOM_ITEM *room)
{
	cJSON *item = cJSON_CreateObject();
	
	cJSON_AddStringToObject(item, FLOOR_ID_STR, (room->floor_id==NULL)?EMPTY_STR:room->floor_id);
	cJSON_AddStringToObject(item, ID_STR, (room->room_id==NULL)?EMPTY_STR:room->room_id);
	cJSON_AddStringToObject(item, ROOM_ICON_STR, (room->room_icon==NULL)?EMPTY_STR:room->room_icon);
	cJSON_AddStringToObject(item, NAME_STR, (room->room_name==NULL)?EMPTY_STR:room->room_name);
	cJSON_AddStringToObject(item, ROOM_STATUS_STR, (room->room_status==NULL)?EMPTY_STR:room->room_status);
	
	return item;
}

static cJSON *_kk_syn_rooms_info(int num,SYN_ROOM_ITEM *rooms)
{
	cJSON *roomsAry = cJSON_CreateArray();
	cJSON *room = NULL;
	int i;
	
	SYN_ROOM_ITEM *item = rooms;

	for(i=0;i<num;i++,item++){
		room = _kk_syn_room_item(item);
		if(room!=NULL){
			cJSON_AddItemToArray(roomsAry,room);
		}
	}
	return roomsAry;
}


cJSON *kk_sync_rooms_to_sdk(cJSON *root,cJSON *data)
{
	cJSON *rooms = cJSON_GetObjectItem(data,ROOMS_STR);
	cJSON *room;
	cJSON *roomId,*name,*devices,*scenes;
	cJSON *roomsAry = NULL;
	
	int i;
	int num = cJSON_GetArraySize(rooms);

	SYN_ROOM_ITEM* items = (SYN_ROOM_ITEM*)malloc(sizeof(SYN_ROOM_ITEM)*num);
	SYN_ROOM_ITEM* item = items;
	memset(item,0,(sizeof(SYN_ROOM_ITEM)*num));

	for(i=0;i<num;i++,item++){
		room = cJSON_GetArrayItem(rooms,i);
		
		roomId = cJSON_GetObjectItem(room,ROOMS_ID_STR);
		name = cJSON_GetObjectItem(room,NAME_STR);
		devices = cJSON_GetObjectItem(room,DEVICES_STR);
		scenes= cJSON_GetObjectItem(room,SCENES_STR);

		//todo
		item->floor_id = NULL; 
		item->room_id = roomId->valuestring;
		item->room_icon = NULL;
		item->room_name = name->valuestring;
		item->room_status = NULL;
	}


	

	roomsAry = _kk_syn_rooms_info(num,items);
	cJSON_AddItemToObject(root, ROOMS_STR, roomsAry);
	return root;
}

/*******场景同步*******/

static cJSON *_kk_scene_action_build(SYN_SCENE_ACTION *act)
{
	SYN_SCENE_ACTION *ptr = act;

	if(ptr->nodeid==-1 || ptr->operation==NULL ||
		ptr->operation==NULL){

		return NULL;
	}
	cJSON *action = cJSON_CreateObject();
	cJSON_AddStringToObject(action, "area",(ptr->ui_area==NULL)?"":ptr->ui_area);
	cJSON_AddStringToObject(action, "name",(ptr->ui_name==NULL)?"":ptr->ui_name);
	cJSON_AddStringToObject(action, "delay",(ptr->delay==NULL)?"0":ptr->delay);
	cJSON_AddNumberToObject(action, "nodeid",ptr->nodeid);
	cJSON_AddStringToObject(action, "operate_type",ptr->operate_type);
	cJSON_AddStringToObject(action, "operation",ptr->operation);
	cJSON_AddStringToObject(action, "room_id",ptr->ui_room_id);
	return action;
}


cJSON *kk_scene_actions_build(SYN_SCENE_ACTION *act,int num)
{
	int i;
	cJSON *actions = cJSON_CreateArray();
	

	//printf("------------------->num:%d\n",num);
	SYN_SCENE_ACTION *ptr=act;
	for(i=0;i<num;i++,ptr++){
		//printf("--------------------------->[%s][%d]\n",__FUNCTION__,__LINE__);
		cJSON * action = _kk_scene_action_build(ptr);
		//printf("--------------------------->[%s][%d]\n",__FUNCTION__,__LINE__);
		cJSON_AddItemToArray(actions,action);
		//printf("--------------------------->[%s][%d]\n",__FUNCTION__,__LINE__);
	}
	//printf("--------------------------->[%s][%d]\n",__FUNCTION__,__LINE__);
	return actions;
}

cJSON *kk_scene_build(SYN_SCENE_ITEM **content)
{
	SYN_SCENE_ITEM *ptr= *content;
	cJSON *scene = cJSON_CreateObject();

	if(content==NULL ||*content==NULL){
		return scene;
	}
	//printf("--------------------------->[%s][%d]\n",__FUNCTION__,__LINE__);
	cJSON *actions = kk_scene_actions_build(ptr->act,ptr->act_num);
	//printf("--------------------------->[%s][%d]\n",__FUNCTION__,__LINE__);
	cJSON_AddItemToObject(scene, "actions",actions);
	cJSON_AddStringToObject(scene, "id",ptr->scene_id);
	cJSON_AddStringToObject(scene, "name",ptr->name);
	cJSON_AddStringToObject(scene, "pannel_id",(ptr->pannel_id==NULL)?"*":ptr->pannel_id);
	cJSON_AddStringToObject(scene, "room_id",ptr->room_id);
	cJSON_AddStringToObject(scene, "scene_image","");
	cJSON_AddStringToObject(scene, "scene_type","100");

	if(ptr->time==NULL){
		cJSON_AddStringToObject(scene, "timer_enable","0");
		cJSON_AddStringToObject(scene, "time","");
	}else{
		cJSON_AddStringToObject(scene, "timer_enable","1");
		cJSON_AddStringToObject(scene, "time",ptr->time);
	}
	cJSON_AddStringToObject(scene, "week",(ptr->week==NULL)?"":ptr->week);
	return scene;
	
}

int kk_sync_actions(cJSON *actions,SYN_SCENE_ACTION **act,char **room_id)
{
	cJSON *deviceCode,*delay,*epNum,*propertyName,*type,*propertyValue,*roomId;

	int i,num = cJSON_GetArraySize(actions);
	int node = -1;
	int get_flag = 0;

	*act = (SYN_SCENE_ACTION *)malloc(sizeof(SYN_SCENE_ACTION)*num);
	memset(*act,0,sizeof(SYN_SCENE_ACTION)*num);

	SYN_SCENE_ACTION *ptr=*act;

	for(i=0;i<num;i++,ptr++){


		cJSON *item;
		item = cJSON_GetArrayItem(actions,i);
	
		deviceCode = cJSON_GetObjectItem(item,"deviceCode");
		delay = cJSON_GetObjectItem(item,"delay");
		epNum = cJSON_GetObjectItem(item,"epNum");
		propertyName= cJSON_GetObjectItem(item,"propertyName");
		type= cJSON_GetObjectItem(item,"type");
		propertyValue= cJSON_GetObjectItem(item,"propertyValue");
		roomId= cJSON_GetObjectItem(item,"roomId");

		ptr->ui_area = NULL;
		ptr->ui_name = NULL;
		ptr->ui_room_id = NULL;
		ptr->delay = delay->valuestring;
		ptr->nodeid = kk_lan_db_node_get(deviceCode->valuestring,epNum->valueint);

		ptr->operate_type ="*";//type->valuestring;//根据实际设备调整
		ptr->operation = "*";//propertyValue->valuestring;//

		if(get_flag==0){
			get_flag = 1;
			*room_id = roomId->valuestring;
		}
	}
	return num;
}





static int kk_sync_scene_condition(cJSON *condition,SYN_SCENE_ITEM **build)
{
	cJSON *itemAry = NULL;
	cJSON *startTime,*endTime,*crossDay,*repeat_days;

	if(condition==NULL ||build==NULL||*build==NULL){
		return -1;
	}

	if((itemAry = cJSON_GetObjectItem(condition,"items"))==NULL){
		return -1;
	}
	
	int i,j,num = cJSON_GetArraySize(itemAry);
	int repeat;
	int get_flag = 0;

	SYN_SCENE_ITEM *ptr=*build;
	
	for(i=0;i<num;i++){
		cJSON *item;

		item = cJSON_GetArrayItem(condition,i);
		startTime = cJSON_GetObjectItem(item,"startTime");
		endTime = cJSON_GetObjectItem(item,"endTime");
		crossDay = cJSON_GetObjectItem(item,"crossDay");
		repeat_days = cJSON_GetObjectItem(item,"repeat_days");
		repeat = repeat_days->valueint;

		if(get_flag==0){
			get_flag = 1;
			char temp[10];
			ptr->week = malloc(32);
			memset(ptr->week,0,32);
			for(j=0;j<7;j++){
				if(repeat&(1<<j)){
					memset(temp,0,10);
					snprintf(temp,10,"%d",j);
					strcat(ptr->week,temp);
				}
			}
		}
	}
	return get_flag;
}




cJSON *kk_sync_scence_to_sdk(cJSON *root,cJSON *data)
{
	cJSON *scenes = cJSON_GetObjectItem(data,SCENES_STR);

	cJSON *actions,*enable,*name,*sceneId,*sceneType,*trigger,*condition;
	
	int i,num = cJSON_GetArraySize(scenes);
	
	SYN_SCENE_ITEM *build= (SYN_SCENE_ITEM *)malloc(sizeof(SYN_SCENE_ITEM)*num);
	if(build == NULL){
		return NULL;
	}
	memset(build,0,sizeof(SYN_SCENE_ITEM)*num);
	
	cJSON *scenesAry = cJSON_CreateArray();
	cJSON *sceneItem;

	SYN_SCENE_ITEM *pScene = build;

	for(i=0;i<num;i++,pScene++){
		printf("i=%d\n",i);
		cJSON *item = cJSON_GetArrayItem(scenes,i);
		actions = cJSON_GetObjectItem(item,ACTIONS_STR);
		enable = cJSON_GetObjectItem(item,ENABLE_STR);
		name = cJSON_GetObjectItem(item,NAME_STR);
		sceneId= cJSON_GetObjectItem(item,SCENE_ID_STR);
		sceneType= cJSON_GetObjectItem(item,SCENE_TYPE_STR);
		trigger= cJSON_GetObjectItem(item,SCENE_TRIGGER_STR);
		condition= cJSON_GetObjectItem(item,CONDITION_STR);

		//todo
		/* 时间段类型
		if(strcmp(sceneType->valuestring,"")==){

		}*/
		pScene->act_num = kk_sync_actions(actions,&pScene->act,&pScene->room_id);

		kk_sync_scene_condition(condition,&pScene);


		pScene->scene_id = sceneId->valuestring;
		pScene->name = name->valuestring;
		pScene->pannel_id = NULL;

		sceneItem = kk_scene_build(&pScene);

		cJSON_AddItemToArray(scenesAry,sceneItem);

	}

	cJSON_AddItemToObject(root, "scenes", scenesAry);
	free(build);
	return root;
}

//同步设备
int _kk_sync_device_item(cJSON *deviceCode,cJSON *epNum,cJSON *name,cJSON *roomId,cJSON *deviceAry)
{
	kk_map_dev_node_t *node = NULL;
	char nodeid[32] = {0};
	char gwmac[32] = {0};
	char submac[32] = {0};


	kk_map_dev_ctx *ctx = _kk_map_dev_ctx();
	
	if(deviceCode == NULL || deviceAry==NULL){
		return -1;
	}

	list_for_each_entry(node, &ctx->dev_list, linked_list, kk_map_dev_node_t) {
		if (node != NULL) {
			if(strlen(node->deviceCode)==strlen(deviceCode->valuestring) &&
				!strcmp(node->deviceCode,deviceCode->valuestring)){
				//空调内机不放入devices
				if(strcmp(node->productCode,"3062") == 0){
					continue;
				}
				cJSON *subdevicesItem = cJSON_CreateObject();

				if(epNum==NULL ||epNum->type!=cJSON_String){
					cJSON_AddStringToObject(subdevicesItem, CHANNEL_STRING, "1");
					kk_creater_nodeid(node->deviceCode,1,nodeid);
				}else{
					cJSON_AddStringToObject(subdevicesItem, CHANNEL_STRING, epNum->valuestring);
					kk_creater_nodeid(node->deviceCode,atoi(epNum->valuestring),nodeid);
				}
				cJSON_AddStringToObject(subdevicesItem, NODEID_STRING, nodeid);

				if(name==NULL ||name->type!=cJSON_String){
					cJSON_AddStringToObject(subdevicesItem, NAME_STRING, "unkown");
				}else{
					cJSON_AddStringToObject(subdevicesItem, NAME_STRING, name->valuestring);
				}
				
				if(name==NULL ||name->type!=cJSON_String){
					cJSON_AddStringToObject(subdevicesItem, ROOM_ID_STRING, "unkown");
				}else{
					cJSON_AddStringToObject(subdevicesItem, ROOM_ID_STRING, roomId->valuestring);
				}

				//todo
				cJSON_AddStringToObject(subdevicesItem, DEVICE_FIELD_STRING, "");
				cJSON_AddStringToObject(subdevicesItem, DEVICE_FIELD_IDNDEX_STRING, "");
				cJSON_AddStringToObject(subdevicesItem, DEVICE_ICON_STRING, "");
				cJSON_AddStringToObject(subdevicesItem, DEVICE_POS_STRING, "");
				_deviceCode_switchto_mac(node->gwDeviceCode,gwmac);
				cJSON_AddStringToObject(subdevicesItem, GW_MAC_STRING, gwmac);
				_deviceCode_switchto_mac(node->deviceCode,submac);
				cJSON_AddStringToObject(subdevicesItem, MAC_STRING, submac);

				cJSON_AddStringToObject(subdevicesItem, OPERATE_TYPE_STRING, node->opearteType);
				cJSON_AddItemToArray(deviceAry, subdevicesItem);
			}
		}
	}
	return 0;
}


int kk_sync_device(cJSON *roomId,cJSON *inDevAry,cJSON *outDevAry)
{
	kk_map_dev_node_t *node = NULL;
	kk_map_dev_ctx *ctx = _kk_map_dev_ctx();
	cJSON *deviceCode = NULL,*epNum = NULL,*name = NULL;
	int i,num;


	if(inDevAry==NULL||inDevAry->type!=cJSON_Array||
		outDevAry==NULL||outDevAry->type!=cJSON_Array){
		return -1;
	}
	num = cJSON_GetArraySize(inDevAry);

	for(i=0;i<num;i++){
		printf("...i=%d\n",i);
		cJSON *item = cJSON_GetArrayItem(inDevAry,i);
		deviceCode = cJSON_GetObjectItem(item,"deviceCode");
		epNum = cJSON_GetObjectItem(item,"epNum");
		name = cJSON_GetObjectItem(item,"name");
		_kk_sync_device_item(deviceCode,epNum,name,roomId,outDevAry);
	}


	return 0;
}

int kk_sync_devices_to_sdk(cJSON *root,cJSON *data)
{
	cJSON *rooms = cJSON_GetObjectItem(data,ROOMS_STR);
	cJSON *deviceAry = cJSON_CreateArray();
	int i,num = cJSON_GetArraySize(rooms);
	cJSON *roomId,*devices;

	for(i=0;i<num;i++){
		cJSON *room = cJSON_GetArrayItem(rooms,i);
		roomId = cJSON_GetObjectItem(room,ROOMS_ID_STR);
		devices = cJSON_GetObjectItem(room,DEVICES_STR);
		kk_sync_device(roomId,devices,deviceAry);
	}

	cJSON_AddItemToObject(root, DEVICES_STRING, deviceAry);
	return 0;
}


//同步设备状态
//
cJSON *_kk_sync_devicestatus_arg_build(kk_map_dev_node_t *node)
{
	int i,num=0,n_num = 0,o_num = 0;
	cJSON *newccu,*oldccu;
	cJSON *arg = cJSON_CreateObject();
	

	if(node == NULL ||node->syn_type!=1||node->syn_opcode==NULL){
		return arg;
	}

	newccu = node->newccu;
	oldccu = node->oldccu;

	if(newccu==NULL||newccu->type!=cJSON_Array ||
		oldccu==NULL||oldccu->type!=cJSON_Array){
		return arg;
	}

	n_num = cJSON_GetArraySize(newccu);
	o_num = cJSON_GetArraySize(oldccu);
	
	num = (n_num>o_num)?o_num:n_num;

	for(i=0;i<num;i++){
		cJSON * newccuItem = cJSON_GetArrayItem(newccu,i);
		cJSON * oldccuItem = cJSON_GetArrayItem(oldccu,i);

		cJSON *val = NULL;

		cJSON *synType = cJSON_GetObjectItem(oldccuItem,"synType");
		cJSON *synKey = cJSON_GetObjectItem(oldccuItem,"syn");
		if(synType){
			if(synType->type!=cJSON_String ||synKey==NULL ||synKey->type!=cJSON_String) {
				continue ;
			}
			//todo:
			if(strcmp(synType->valuestring,"timing_shutdown")==0) {
				cJSON *syn_obj = cJSON_CreateObject();

				double t=cJSON_GetObjectItem(newccuItem,"value")->valuedouble;
				char buff[32]={0};

				snprintf(buff,32,"%f",t);
					
				if(t>0){
					cJSON_AddBoolToObject(syn_obj, "enable",1);
					cJSON_AddStringToObject(syn_obj, "time",buff);
				}else{
					cJSON_AddBoolToObject(syn_obj, "enable",0);
					cJSON_AddNullToObject(syn_obj, "time");
				}

				cJSON_AddItemToObject(arg, synKey->valuestring,syn_obj);
				
			}else{
				if((val = val_conver_new2old(newccuItem,oldccuItem,1))!=NULL){
					kk_lan_add_val_to_obj(arg,val,synKey->valuestring);
				}
			}
		}
	}
	return arg;
}


static int _kk_sync_devices_status_arg_str(kk_map_dev_node_t *node,cJSON *devStatusAry,int *index)
{
	int i,num = 0;

	cJSON *newccu = NULL,*oldccu = NULL;
	cJSON *dev_status = NULL;
	

	if(node == NULL ||devStatusAry==NULL||index==NULL){
		return -1;
	}

	newccu = node->newccu;
	oldccu = node->oldccu;

	if(newccu==NULL||newccu->type!=cJSON_Array ||
		oldccu==NULL||oldccu->type!=cJSON_Array){
		return -2;
	}

	num = cJSON_GetArraySize(newccu);
		printf("[%s][%d]\n",__FUNCTION__,__LINE__);
	for(i=0;i<num;i++){
		cJSON * newccuItem = cJSON_GetArrayItem(newccu,i);
		cJSON * oldccuItem = cJSON_GetArrayItem(oldccu,i);
		
		cJSON *val = NULL;
		printf("[%s][%d]\n",__FUNCTION__,__LINE__);
		if((val = val_conver_new2old(newccuItem,oldccuItem,0))!=NULL){
			printf("[%s][%d]\n",__FUNCTION__,__LINE__);
			char indexId[4] = {0};
			char nodeid[32] = {0};
			cJSON *epNum = cJSON_GetObjectItem(newccuItem,CHANNEL_STRING);
			cJSON *opcode = cJSON_GetObjectItem(newccuItem,OPCODEMAP_STRING);

			if(opcode==NULL||opcode->type!=cJSON_String||
				epNum==NULL ||epNum->type!=cJSON_String){
				continue ;
			}
		
			dev_status = cJSON_CreateObject();
			kk_lan_add_val_to_obj(dev_status,val,"arg");

			kk_creater_nodeid(node->deviceCode,atoi(epNum->valuestring),nodeid);
			
			cJSON_AddStringToObject(dev_status, OPCODE_STRING,opcode->valuestring);
			cJSON_AddNumberToObject(dev_status, NODEID_STRING, atoi(nodeid));
			memset(indexId,0,sizeof(indexId));
			snprintf(indexId,sizeof(indexId),"%d",*index);
			*index += 1;
			cJSON_AddStringToObject(dev_status, "index", indexId);

			cJSON_AddItemToArray(devStatusAry,dev_status);
		}
	}
	return 0;
}





static int _kk_sync_devices_status_arg_obj(kk_map_dev_node_t *node,cJSON *devStatusAry,int *aryIx)
{
	char indexId[4] = {0};
	char nodeid[32] = {0};
	cJSON *arg = NULL;
	cJSON *dev_status = NULL;

	if(node==NULL ||devStatusAry==NULL||aryIx==NULL){
		return -1;
	}

	if((arg = _kk_sync_devicestatus_arg_build(node))==NULL){
		return -2;
	}
	dev_status = cJSON_CreateObject();
	
	cJSON_AddItemToObject(dev_status,ARG_STRING,arg);
	cJSON_AddStringToObject(dev_status, OPCODE_STRING,node->syn_opcode);

	kk_creater_nodeid(node->deviceCode,1,nodeid);
	cJSON_AddNumberToObject(dev_status, NODEID_STRING, atoi(nodeid));
	
	memset(indexId,0,sizeof(indexId));
	snprintf(indexId,sizeof(indexId),"%d",*aryIx);
	*aryIx+=1;
	cJSON_AddStringToObject(dev_status, "index", indexId);
	
	cJSON_AddItemToArray(devStatusAry,dev_status);
	return 0;
}

int kk_sync_devices_status_to_sdk(cJSON *root)
{
	int idx = 1;
	kk_map_dev_node_t *node = NULL;	
	kk_map_dev_ctx *ctx = _kk_map_dev_ctx();
	kk_map_dev_node_t *n = NULL;

	cJSON *devStatusAry = cJSON_CreateArray();

	_kk_map_dev_mutex_lock();
	list_for_each_entry_safe(node,n, &ctx->dev_list, linked_list, kk_map_dev_node_t){

		if(node->syn_type==1){
			_kk_sync_devices_status_arg_obj(node,devStatusAry,&idx);
		}else{
			_kk_sync_devices_status_arg_str(node,devStatusAry,&idx);
			//_kk_sync_devicestatus(node,devStatusAry);

		}
	}
	_kk_map_dev_mutex_unlock();
	cJSON_AddItemToObject(root, DEVICE_STATUS_STRING, devStatusAry);
	

	return 0;
}


//同步网关版本
cJSON *kk_sync_gw_version_to_sdk(cJSON *root,cJSON *data)
{
	cJSON *devicesAry = cJSON_GetObjectItem(data,DEVICES_STR);

	cJSON *gw_version = cJSON_CreateArray();
	int i,gw_num;
	if(devicesAry->type!=cJSON_Array){
		return NULL;
	}

	gw_num = cJSON_GetArraySize(devicesAry);

	for(i=0;i<gw_num;i++){
		cJSON *version = cJSON_CreateObject();
		
		cJSON *item = cJSON_GetArrayItem(devicesAry,i);

		//todo:下载版本,运行版本,网关类型转换
		cJSON *run_version = cJSON_GetObjectItem(item,"firmwareVersion");
		cJSON *download_version = cJSON_GetObjectItem(item,"firmwareVersion");
		cJSON *gw_mac = cJSON_GetObjectItem(item,"mac");
		cJSON *gw_type = cJSON_GetObjectItem(item,"name");

		cJSON_AddStringToObject(version,"run_version",(run_version->valuestring)?run_version->valuestring:"");
		cJSON_AddStringToObject(version,"download_version",(download_version->valuestring)?download_version->valuestring:"");
		cJSON_AddStringToObject(version,"gw_mac",(gw_mac->valuestring)?gw_mac->valuestring:"");
		cJSON_AddStringToObject(version,"gw_type",(gw_type->valuestring)?gw_type->valuestring:"");
		cJSON_AddItemToArray(gw_version,version);
	}

	cJSON_AddItemToObject(root, "gw_version", gw_version);

	return root;
}

//同步ccu版本
cJSON *kk_sync_ccu_version_to_sdk(cJSON *root,cJSON *data)
{
	//todo:同步CCU版本信息
	cJSON *ccu_version = cJSON_CreateObject();
	cJSON_AddStringToObject(ccu_version, "cur_ccu_version", "1.0.0"); 
	cJSON_AddStringToObject(ccu_version, "downloaded_ccu_version", "1.0.0"); 
	cJSON_AddItemToObject(root, "ccu_version", ccu_version);

	return root;
}


#define GUARD_LEAVE_HOME				1 //离家布防
#define UNGUARD							2 //撤防
#define GUARD_AT_HOME					3 //在家布防
#define GUARD_CUSTOM					4 //自定义防区布防

/*
1：在家安防传感器，
2：室外安防传感器，
3：24小时安防传感器。
4：24小时不告警传感器。
*/
typedef struct{
	char *nodeId;
	char *sensor_type;
}SYN_GUARD_SENSORS;
static int _kk_guard_sensors_build(cJSON *guard_sensors,int num,SYN_GUARD_SENSORS *sensors)
{
	int i;
	SYN_GUARD_SENSORS *pSensor;

	if(num<=0 || sensors==NULL){
		return -1;
	}
	
	pSensor = sensors;
	for(i=0;i<num;i++,pSensor++){
		cJSON *item = cJSON_CreateObject();
		cJSON_AddStringToObject(item,"nodeid",(pSensor->nodeId)?pSensor->nodeId:"-1");
		cJSON_AddStringToObject(item,"sensor_type",(pSensor->sensor_type)?pSensor->sensor_type:"0");
		cJSON_AddItemToArray(guard_sensors,item);
	}
	return 0;
}



int kk_sync_guard_to_sdk(cJSON *root,cJSON *data)
{
	char *armingStr = NULL;
	
	cJSON *guard = cJSON_CreateObject();
	cJSON *custom_guard_zone = cJSON_CreateArray();
	cJSON *guard_sensors = cJSON_CreateArray();
	
	cJSON *properties = cJSON_GetObjectItem(data,"properties");
	cJSON *ArmingState = NULL,*RoomIdsAry = NULL;
	
	cJSON_AddStringToObject(guard, "arming_status", "1");
	cJSON_AddItemToObject(guard,"custom_guard_zone",custom_guard_zone);
	cJSON_AddItemToObject(guard,"guard_sensors",guard_sensors);
	
	cJSON_AddItemToObject(root, "guard", guard);

	if(properties==NULL||properties->type!=cJSON_Object){
		return -1;
	}

	ArmingState = cJSON_GetObjectItem(properties,"ArmingState");
	if(ArmingState==NULL||ArmingState->type!=cJSON_Number){
		return -1;
	}

	/*
	"0": "离家布防",
	"1": "撤防",
	"2": "在家布防",
	"3": "区域布防"
	*/
	//1：离家布防，2：撤防，3：在家布防，4：自定义防区布防。
	
	if(ArmingState->valueint==0){
		armingStr = "1";
	}else if(ArmingState->valueint==2){
		armingStr = "3";
	}else if(ArmingState->valueint==3){
		armingStr = "4";
	}else {
		armingStr = "2";
	}
	
	cJSON_ReplaceItemInObject(guard, "arming_status", cJSON_CreateString(armingStr));
	if(ArmingState->valueint == 3){
		int i,num;
		cJSON *item = NULL;
		char roomIdStr[16] = {0};
		RoomIdsAry = cJSON_GetObjectItem(properties,"RoomIds");
		if(RoomIdsAry==NULL||RoomIdsAry->type!=cJSON_Array){
			return -1;
		}
		num = cJSON_GetArraySize(RoomIdsAry);
		for(i=0;i<num;i++){
			item = cJSON_GetArrayItem(RoomIdsAry,i);
			if(item->type!=cJSON_Number){
				continue ;
			}
			memset(roomIdStr,0,sizeof(roomIdStr));
			snprintf(roomIdStr,sizeof(roomIdStr),"%d",item->valueint);
			cJSON_AddItemToArray(custom_guard_zone,cJSON_CreateString(roomIdStr));
		}
	}
	//新中控同步接口未有安防类传感器列表,故只保留实现接口,未具体实现转换
	_kk_guard_sensors_build(guard_sensors,-1,NULL);
	return 0;
}



//同步空调网关
typedef struct{
	char *node;
	char *dev_name;
	char *id;
	char *room_id;
	cJSON * status;
}SYN_CENTRAL_AC_GW;
cJSON *_kk_sync_central_ac_gw(SYN_CENTRAL_AC_GW *gw)
{
	cJSON *item = cJSON_CreateObject();
	cJSON *status;

	cJSON_AddStringToObject(item, "bind_central_ac_gw_node_id",(gw->node)?gw->node:"");
	cJSON_AddStringToObject(item, "dev_name", (gw->dev_name)?gw->dev_name:"");
	cJSON_AddStringToObject(item, "id", (gw->id)?gw->id:"");
	cJSON_AddStringToObject(item, "room_id", (gw->room_id)?gw->room_id:"");

	cJSON_AddItemToObject(item, "status",gw->status?gw->status:cJSON_CreateNull());
	return item;
}

static int kk_get_roomInfo_by_deviceCode(cJSON *data,char *pdeviceCode,char*roomId)
{
	cJSON *rooms = cJSON_GetObjectItem(data,"rooms");
	cJSON * item = rooms->child;
	while(item != NULL){
		cJSON *devices = cJSON_GetObjectItem(item,"devices");
		if(devices == NULL){
			return -1;
		}
		cJSON * subitem = devices->child;
		while(subitem != NULL){
			cJSON *deviceCode = cJSON_GetObjectItem(subitem,"deviceCode");
			if(deviceCode != NULL && !strcmp(deviceCode->valuestring,pdeviceCode))
			{
				cJSON *roomIdJ = cJSON_GetObjectItem(item,"roomId");
				memcpy(roomId,roomIdJ->valuestring,strlen(roomIdJ->valuestring));
			}
			return 0;
		}
	}
	return -1;
}
new_dev_item g_new_item[16] = {0};
CENTRAL_AC_INDOOR_ITEM *g_indoor_item = NULL;
int g_newgw_count = 0;
int g_indoor_count = 0;
void kk_clear_indoor_data()
{
	memset(g_new_item,0x0,sizeof(new_dev_item)*16);
	if(g_indoor_item != NULL){
		free(g_indoor_item);
		g_indoor_item = NULL;
	}
	g_newgw_count = 0;
	g_indoor_count = 0;
}
void kk_create_new_central_ac(char *gwDeviceCode,char *deviceCode,char *nodeId)
{
	char gwmac[32] = {0};
	char submac[32] = {0};
	if(g_newgw_count > 16){
		return;
	}
	//printf("------------------CWC------------------------>[%s][%d]\n",__FUNCTION__,__LINE__);
	_deviceCode_switchto_mac(gwDeviceCode,gwmac);
	_deviceCode_switchto_mac(deviceCode,submac);
	memcpy(g_new_item[g_newgw_count].gwmac,gwmac,strlen(gwmac));
	memcpy(g_new_item[g_newgw_count].mac,submac,strlen(submac));
	memcpy(g_new_item[g_newgw_count].channel,"1",strlen("1"));
	memcpy(g_new_item[g_newgw_count].operate_type,"12001",strlen("12001"));
	memcpy(g_new_item[g_newgw_count].nodeid,nodeId,strlen(nodeId));
	g_newgw_count++;
	//printf("------------------CWC------------------------>[%s][%d]\n",__FUNCTION__,__LINE__);
	return;
}
int kk_sync_indoor_status(cJSON* eps){

}
char *modeMap[] = {
	"AUTO",
	"COLD",
	"HOT",
	"AIR_SUPPLY",
	"DEHUMIDIFICATION",
	"UNKONWN"
};
char *speedMap[] = {
	"AUTO",
	"UNKONWN",
	"LOW",
	"MID",
	"HIGH",
	"UNKONWN",
	"UNKONWN",
};
int kk_send_indoorAir_status(cJSON *info)
{
	char epStr[4] = {0};
	if(info == NULL){
		return -1;
	}
	cJSON *root = cJSON_CreateObject();
	cJSON *epNum =  cJSON_GetObjectItem(info,"epNum");
	cJSON_AddStringToObject(root, "nodeid", epNum->valuestring);	
	cJSON_AddStringToObject(root, "opcode", "CENTRAL_AC_INDOOR_UNIT_STATUS");	
	cJSON_AddStringToObject(root, "status", "success");	
	cJSON *arg = cJSON_CreateObject();
	cJSON_AddBoolToObject(arg, "online", 1);	
	cJSON *PowerSwitch =  cJSON_GetObjectItem(info,"PowerSwitch");
	cJSON_AddBoolToObject(arg, "on", PowerSwitch->valueint);	
	cJSON *Temperature =  cJSON_GetObjectItem(info,"Temperature");
	cJSON_AddNumberToObject(arg,"settingTemperature",Temperature->valuedouble);
	cJSON *CurrentTemperature =  cJSON_GetObjectItem(info,"CurrentTemperature");
	cJSON_AddNumberToObject(arg,"roomTemperature",CurrentTemperature->valuedouble);
	cJSON *WindSpeed =  cJSON_GetObjectItem(info,"WindSpeed");
	cJSON_AddStringToObject(arg, "fanSpeed", speedMap[WindSpeed->valueint]);	
	cJSON *WorkMode =  cJSON_GetObjectItem(info,"WorkMode");
	cJSON_AddStringToObject(arg, "runModel", modeMap[WorkMode->valueint]);	
	cJSON_AddItemToObject(root, "arg", arg);
	send_msg_to_module(root);
	cJSON_Delete(root);	
	return 0;

}
cJSON *kk_sync_central_ac_to_sdk(cJSON *root,cJSON *data)
{
	int gw_num = 0,i = 0;
	int sub_num = 0,j = 0;
	int k = 0;
	char nodeid[8] = {0};
	char roomId[32] = {0};
	char deviceName[256] = {0};
	char epStr[4] = {0};
	cJSON *central_ac_gws = cJSON_CreateArray();
	SYN_CENTRAL_AC_GW ac;
	if(data == NULL){
		return NULL;
	}
	kk_clear_indoor_data();
	cJSON *gwAry = cJSON_GetObjectItem(data,DEVICES_STR);
	if(gwAry == NULL) return NULL;
	gw_num = cJSON_GetArraySize(gwAry);
	for(i = 0; i < gw_num; i++){
		cJSON *gwitem = cJSON_GetArrayItem(gwAry,i);
		cJSON *gwDeviceCode = cJSON_GetObjectItem(gwitem,"deviceCode");
		if(gwitem == NULL) return NULL;
		cJSON *subAry = cJSON_GetObjectItem(gwitem,DEVICES_STR);
		if(subAry == NULL) return NULL;
		sub_num = cJSON_GetArraySize(subAry);
		for(j = 0; j < sub_num; j++){
			cJSON *subitem = cJSON_GetArrayItem(subAry,j);
			if(subitem == NULL) return NULL;
			cJSON *productCode = cJSON_GetObjectItem(subitem,"productCode");
			if(productCode != NULL && strcmp(productCode->valuestring,"3062") == 0){//空调网关设备
				cJSON *deviceCode = cJSON_GetObjectItem(subitem,"deviceCode");
				kk_creater_nodeid(deviceCode->valuestring,1,nodeid);
				cJSON *properties = cJSON_GetObjectItem(subitem,"properties");
				cJSON *indoorItem = cJSON_CreateObject();	
				kk_get_roomInfo_by_deviceCode(data,deviceCode->valuestring,roomId);
				cJSON_AddStringToObject(indoorItem, "bind_central_ac_gw_node_id",nodeid);
				cJSON_AddStringToObject(indoorItem, "dev_name", "空调网关");
				cJSON_AddStringToObject(indoorItem, "id", nodeid);
				cJSON_AddStringToObject(indoorItem, "room_id", roomId);								
				cJSON_AddItemToArray(central_ac_gws,indoorItem);	
				
				cJSON *epsAry = cJSON_GetObjectItem(properties,"eps");
				cJSON *EpTotal = cJSON_GetObjectItem(properties,"EpTotal");
				int epsize = cJSON_GetArraySize(epsAry);
				g_indoor_item = (CENTRAL_AC_INDOOR_ITEM *)malloc(sizeof(CENTRAL_AC_INDOOR_ITEM)*epsize);
				if(g_indoor_item == NULL){
					return NULL;
				}
				memset(g_indoor_item,0x0,sizeof(CENTRAL_AC_INDOOR_ITEM)*epsize);
				g_indoor_count = epsize;
				for(k = 0; k < epsize; k++){
					char tmpIdx[4] = {0};
					cJSON *infoItem = cJSON_GetArrayItem(epsAry,k);
					if(infoItem == NULL) continue;
					cJSON *epNum =  cJSON_GetObjectItem(infoItem,"epNum");
					memset(epStr,0x0,sizeof(epStr));
					sprintf(epStr,"%d",epNum->valueint);
					memcpy(g_indoor_item[k].id,epStr,strlen(epStr));
					sprintf(tmpIdx,"%d",k);
					memcpy(g_indoor_item[k].indooruint_addr,tmpIdx,strlen(tmpIdx));
					memcpy(g_indoor_item[k].nodeid,nodeid,strlen(nodeid));
					cJSON *PowerSwitch =  cJSON_GetObjectItem(infoItem,"PowerSwitch");
					g_indoor_item[k].ac_gw_status.on = PowerSwitch->valueint == 1?true:false;
					g_indoor_item[k].ac_gw_status.online = 1;
					cJSON *Temperature =  cJSON_GetObjectItem(infoItem,"Temperature");
					cJSON *CurrentTemperature =  cJSON_GetObjectItem(infoItem,"CurrentTemperature");
					g_indoor_item[k].ac_gw_status.settingTemperature = Temperature->valuedouble;
					g_indoor_item[k].ac_gw_status.roomTemperature = CurrentTemperature->valuedouble;
					cJSON *WindSpeed =  cJSON_GetObjectItem(infoItem,"WindSpeed");
					memcpy(g_indoor_item[k].ac_gw_status.speed,speedMap[WindSpeed->valueint],strlen(speedMap[WindSpeed->valueint]));
					cJSON *WorkMode =  cJSON_GetObjectItem(infoItem,"WorkMode");
					memcpy(g_indoor_item[k].ac_gw_status.mode,modeMap[WorkMode->valueint],strlen(modeMap[WorkMode->valueint]));
				}
				kk_create_new_central_ac(gwDeviceCode->valuestring,deviceCode->valuestring,nodeid);
			}
		}
	}
	cJSON_AddItemToObject(root, "central_ac_gws", central_ac_gws);
	return root;
}

//同步空调网关内机
typedef struct{
	char *id;
	char *room_id;
	char *indoorunit_name;
	char *indooruint_addr;
	char *central_ac_gw_devid;
	cJSON * indoorunit_state;
}SYN_CENTRAL_AC_INDOOR;
cJSON *_kk_sync_central_ac_indoorunit_to_sdk(SYN_CENTRAL_AC_INDOOR* indoorunit)
{
	cJSON *item = cJSON_CreateObject();
	cJSON *status;

	cJSON_AddStringToObject(item, "id",(indoorunit->id)?indoorunit->id:"");
	cJSON_AddStringToObject(item, "room_id", (indoorunit->room_id)?indoorunit->room_id:"");
	cJSON_AddStringToObject(item, "indoorunit_name", (indoorunit->indoorunit_name)?indoorunit->indoorunit_name:"");
	cJSON_AddStringToObject(item, "indooruint_addr", (indoorunit->indooruint_addr)?indoorunit->indooruint_addr:"");
	cJSON_AddStringToObject(item, "central_ac_gw_devid", (indoorunit->central_ac_gw_devid)?indoorunit->central_ac_gw_devid:"");

	cJSON_AddItemToObject(item, "indoorunit_state",(indoorunit->indoorunit_state)?indoorunit->indoorunit_state:cJSON_CreateNull());
	return item;
}
cJSON *_kk_sync_central_ac_indoorunits(int num,SYN_CENTRAL_AC_INDOOR *indoorunits)
{
	int i;
	cJSON *central_ac_indoorunits = cJSON_CreateArray();
	SYN_CENTRAL_AC_GW *indoorunit = indoorunits;
	
	for(i=0;i<num;i++,indoorunit++) {
		cJSON *item =_kk_sync_central_ac_indoorunit_to_sdk(indoorunit);
		cJSON_AddItemToArray(central_ac_indoorunits,item);
	}

	return central_ac_indoorunits;
}

cJSON *kk_sync_central_ac_indoorunits_to_sdk(cJSON *root,cJSON *data)
{
	cJSON *central_ac_indoorunits;
	central_ac_indoorunits = cJSON_CreateArray();


	SYN_CENTRAL_AC_INDOOR indoorunit;
	indoorunit.id = malloc(20);
	memset(indoorunit.id,0,20);
	memcpy(indoorunit.id,"4",sizeof("4"));
	
	indoorunit.room_id = malloc(20);
	memset(indoorunit.room_id,0,20);
	memcpy(indoorunit.room_id,"44",sizeof("44"));
	
	indoorunit.indoorunit_name = malloc(20);
	memset(indoorunit.indoorunit_name,0,20);
	memcpy(indoorunit.indoorunit_name,"444",sizeof("444"));
	
	indoorunit.indooruint_addr = malloc(20);
	memset(indoorunit.indooruint_addr,0,20);
	memcpy(indoorunit.indooruint_addr,"4444",sizeof("4444"));

	indoorunit.central_ac_gw_devid = malloc(20);
	memset(indoorunit.central_ac_gw_devid,0,20);
	memcpy(indoorunit.central_ac_gw_devid,"44444",sizeof("44444"));

	
	indoorunit.indoorunit_state = NULL;

	central_ac_indoorunits = _kk_sync_central_ac_indoorunits(1,&indoorunit);
	cJSON_AddItemToObject(root, "central_ac_indoorunits", central_ac_indoorunits);	  

	return root;
}

//同步组
typedef struct{
	char *id;
	char *name;
	cJSON * nodes;
}SYN_GROUP;

cJSON *_kk_sync_group_nodes(int num,char* list[])
{
	int i;
	cJSON *nodesAry = cJSON_CreateArray();

	for(i=0;i<num;i++){
		cJSON *item = cJSON_CreateObject();
		cJSON_AddStringToObject(item, "nodeid", (list[i])?list[i]:"");
		cJSON_AddItemToArray(nodesAry,item);
	}
	return nodesAry;
}

cJSON *_kk_sync_group_to_sdk(SYN_GROUP *group)
{
	cJSON *item = cJSON_CreateObject();
	
	cJSON_AddStringToObject(item, "id", (group->id)?group->id:"");
	cJSON_AddStringToObject(item, "name", (group->name)?group->name:"");
	cJSON_AddItemToObject(item, "nodes", group->nodes?group->nodes:cJSON_CreateNull());
	return item;
}

cJSON *_kk_sync_groups(int num,SYN_GROUP *group)
{
	int i;
	cJSON *groups = cJSON_CreateArray();
	SYN_GROUP *pGrp = group;
	for(i=0;i<num;i++,pGrp++){
		cJSON *item = _kk_sync_group_to_sdk(pGrp);
		cJSON_AddItemToArray(groups,item);
	}
	return groups;
}

cJSON *kk_sync_groups_to_sdk(cJSON *root,cJSON *data)
{

	cJSON *groups = NULL;

	SYN_GROUP grp;

	grp.id = malloc(20);
	memset(grp.id,0,20);
	memcpy(grp.id,"1",sizeof("1"));

	grp.name = malloc(20);
	memset(grp.name,0,20);
	memcpy(grp.name,"2",sizeof("2"));


	char *list[2];
	list[0] = malloc(20);
	memset(list[0],0,20);
	memcpy(list[0],"x",sizeof("x"));

	list[1] = malloc(20);
	memset(list[1],0,20);
	memcpy(list[1],"y",sizeof("y"));

	grp.nodes=_kk_sync_group_nodes(2,list);
	groups = _kk_sync_groups(1,&grp);


	cJSON_AddItemToObject(root, "group", groups);
	return root;
}

//楼层信息
typedef struct{
	char *floor_icon;
	char *floor_2_bg;
	char * floor_pos;
	char * id;
	char *name;
}SYN_FLOOR;

static cJSON * kk_create_floor_obj(SYN_FLOOR *floor)
{
	cJSON *item = cJSON_CreateObject();
	
	cJSON_AddStringToObject(item, "floor_icon", (floor->floor_icon)?floor->floor_icon:"");
	cJSON_AddStringToObject(item, "floor_2_bg", (floor->floor_2_bg)?floor->floor_2_bg:"");
	cJSON_AddStringToObject(item, "floor_pos", (floor->floor_pos)?floor->floor_pos:"");
	cJSON_AddStringToObject(item, "id", (floor->id)?floor->id:"");
	cJSON_AddStringToObject(item, "name", (floor->name)?floor->name:"");

	return item;

}

static int kk_create_floors(int num ,SYN_FLOOR *floor)
{
	int i;
	cJSON *floors = cJSON_CreateArray();
	SYN_FLOOR * pFlr = floor;
	for(i=0;i<num;i++,pFlr++){
		 cJSON * item = kk_create_floor_obj(pFlr);
		cJSON_AddItemToArray(floors,item);
	}
	
	return floors;
}

static int kk_create_floors_to_sdk(cJSON *root,cJSON *data)
{
	cJSON *floors = NULL;

	SYN_FLOOR flr;
	memset(&flr,0,sizeof(SYN_FLOOR));
	flr.floor_2_bg = malloc(20);
	memset(flr.floor_2_bg,0,20);
	memcpy(flr.floor_2_bg,"1",sizeof("1"));
	
	
	flr.floor_icon= malloc(20);
	memset(flr.floor_icon,0,20);
	memcpy(flr.floor_icon,"2",sizeof("2"));
	
	flr.floor_pos= malloc(20);
	memset(flr.floor_pos,0,20);
	memcpy(flr.floor_pos,"3",sizeof("3"));
	flr.id= malloc(20);
	memset(flr.id,0,20);
	memcpy(flr.id,"4",sizeof("4"));
	flr.name= malloc(20);
	memset(flr.name,0,20);
	memcpy(flr.name,"一楼",sizeof("一楼"));

	floors = kk_create_floors(1,&flr);
	
	cJSON_AddItemToObject(root, "floors", floors);
	return 0;
}


//同步数据
int kk_create_syncinfo_to_sdk(cJSON *payload)
{
	cJSON *air_box_devices;
	cJSON *alarms;
	cJSON *ccu_link_status;
	cJSON *link_arg;

	cJSON *cnwise_music_controllers;
	cJSON *code_lib_controllers;
	cJSON *controllers;
	cJSON *expand_rules;
	cJSON *data = kk_get_sync_data(payload);



	cJSON *root=cJSON_CreateObject();
	cJSON *aiks_controllers = cJSON_CreateArray();
	cJSON_AddItemToObject(root, "aiks_controllers", aiks_controllers);
	air_box_devices = cJSON_CreateArray();
	cJSON_AddItemToObject(root, "air_box_devices", air_box_devices);
	alarms = cJSON_CreateArray();
	cJSON_AddItemToObject(root, "alarms", alarms); 
	ccu_link_status = cJSON_CreateObject(); 
	link_arg = cJSON_CreateObject(); 
	cJSON_AddItemToObject(ccu_link_status, "link_arg", link_arg);
	cJSON_AddStringToObject(ccu_link_status, "link_type", "broadband_net");
	cJSON_AddItemToObject(root, "ccu_link_status", ccu_link_status);

	printf("[%s][%d]\n",__FUNCTION__,__LINE__);
	


	cnwise_music_controllers = cJSON_CreateArray();
	cJSON_AddItemToObject(root, "cnwise_music_controllers", cnwise_music_controllers);       
	code_lib_controllers = cJSON_CreateArray();
	cJSON_AddItemToObject(root, "code_lib_controllers", code_lib_controllers);     


	controllers = cJSON_CreateArray();
	cJSON_AddItemToObject(root, "controllers", controllers);  
	




	

	kk_sync_devices_status_to_sdk(root);



	kk_sync_devices_to_sdk(root,data);




	kk_sync_rooms_to_sdk(root,data);


	kk_sync_scence_to_sdk(root,data);


	kk_sync_gw_version_to_sdk(root,data);

	kk_sync_ccu_version_to_sdk(root,data);



	kk_sync_guard_to_sdk(root,data);

	kk_sync_central_ac_to_sdk(root,data);

	kk_sync_central_ac_indoorunits_to_sdk(root,data);


	kk_sync_groups_to_sdk(root,data);


	kk_create_floors_to_sdk(root,data);


	#if 1 

	expand_rules = cJSON_CreateArray();

	cJSON_AddItemToObject(root, "expand_rules", expand_rules);

	


	#endif
	char *out=cJSON_Print(root);
	cJSON *msg = old_ccu_msg_build_json("*","SYNC_INFO",NULL,root);
	send_msg_to_module(msg);
	cJSON_Delete(msg);
	free(out);
	if(g_indoor_count > 0){
		sleep(1);
		kk_new_device_send();
	}
	return 0;
}














