/*******************************************************************************
 * Copyright (c) 2012, 2020 IBM Corp.
 *
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v2.0
 * and Eclipse Distribution License v1.0 which accompany this distribution.
 *
 * The Eclipse Public License is available at
 *   https://www.eclipse.org/legal/epl-2.0/
 * and the Eclipse Distribution License is available at
 *   http://www.eclipse.org/org/documents/edl-v10.php.
 *
 * Contributors:
 *    Ian Craggs - initial contribution
 *******************************************************************************/

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include "MQTTAsync.h"
#include "mqtt_api.h"
#include "com_api.h"
#include "kk_product.h"
#include "kk_hal.h"
//#include "kcloud_log.h"
static char s_ccuid[DEVICE_CODE_LEN] = {0};
int KK_Get_ccuid(char *device_code)
{
	strncpy(device_code, s_ccuid, strlen(s_ccuid));
	INFO_PRINT("HAL_Get_ccuid:%s\n",s_ccuid);
	return strlen(s_ccuid);
}
static int _setDevice_Code(_IN_ char *device_code,int len)
{
	memset(s_ccuid, 0x0, DEVICE_CODE_LEN);
	INFO_PRINT("_setDevice_Code:%s\n",device_code);
	strncpy(s_ccuid, device_code, len);
	return len;
}
static int KK_Ccuid_init(void)
{
	char ccuid[DEVICE_CODE_LEN] = {0};
	char ccuidTmp[DEVICE_CODE_LEN] = {0};
	int ccuid_len = 0;
	#ifdef CONFIG_A133_PLATFORM
    uint8_t data[128] = {0};
    int data_len = 0;
	char *pstart = NULL;
	char *pEnd = NULL;
    HAL_Execel_cmd(GET_CCUID_CMD,(char *)data,sizeof(data),&data_len);
    INFO_PRINT("---GET_CCUID_CMD:%s\n",data);
    if(data_len > 0 && data_len <= 128){
		pstart = data;
		pEnd = strstr(data,"-");
		if(pstart != NULL && pEnd != NULL){
			printf("-------123---------------------\n");
			memcpy(ccuidTmp,pstart,pEnd-pstart);
			_setDevice_Code(ccuidTmp,pEnd-pstart);
		}else{
        	//_setDevice_Code(KK_CCU_ID,strlen(KK_CCU_ID));
			INFO_PRINT("KK_Ccuid_init get ccuid error\n");
			return -1;
		}
    }else{
        //_setDevice_Code(KK_CCU_ID,strlen(KK_CCU_ID));
		INFO_PRINT("KK_Ccuid_init get ccuid error\n");
		return -1;
    }
	#else
	HAL_Execel_cmd(GET_CCUID_CMD,(char *)ccuid,sizeof(ccuid),&ccuid_len);
	printf("GET_CCUID_CMD:%s\n",ccuid);
	if(ccuid_len > 0 && ccuid_len <= DEVICE_CODE_LEN){
		sprintf(ccuidTmp,"CCU_%s",ccuid);
		_setDevice_Code(ccuidTmp,strlen(ccuidTmp)-1);//减一是因为最后有一个换行
	}else{
		//_setDevice_Code(KK_CCU_ID,strlen(KK_CCU_ID));
		INFO_PRINT("KK_Ccuid_init get ccuid error\n");
		return -1;
	}
	#endif
	return 0;
}
char s_pid[PRODUCT_CODE_LEN] = {0};
static int kk_cloud_pid_init(void)
{
	char pid[PRODUCT_CODE_LEN] = {0};
    int pid_len = 0;
    HAL_Execel_cmd(GET_PRODUCTID_CMD,(char *)pid,sizeof(pid),&pid_len);
    if(pid_len > 0 && pid_len <= PRODUCT_CODE_LEN){
		memcpy(s_pid,pid,pid_len-1);
		INFO_PRINT("s_pid:%s\n",s_pid);
    }else{
		return -1;
    }
	return 0;
}
int kk_cloud_get_pid(char *productId)
{
	strncpy(productId, s_pid, strlen(s_pid));
	printf("kk_cloud_get_pid:%s\n",s_pid);
	return strlen(s_pid);
}
char s_key[128] = {0};
static int kk_cloud_key_init(void)
{
	uint8_t key[128] = {0};
    int key_len = 0;
	#ifdef CONFIG_A133_PLATFORM
	char *pstart = NULL;
	char *pEnd = NULL;
    HAL_Execel_cmd(GET_CCUID_CMD,(char *)key,sizeof(key),&key_len);
    INFO_PRINT("---productSecret:%s\n",key);
    if(key_len > 0 && key_len <= 128){
		pstart = key;
		pEnd = strstr(key,"key_");
		if(pEnd != NULL){
			memcpy(s_key,pEnd+4,key_len-(pEnd-pstart+4));
			if (s_key[key_len-(pEnd-pstart+4) -1] == '\n'){
				s_key[key_len-(pEnd-pstart+4) -1] = '\0';
				INFO_PRINT("kk_cloud_key_init remove entry\n");
			}
			INFO_PRINT("kk_cloud_key_init s_key:%s\n",s_key);
		}else{
        	//_setDevice_Code(KK_CCU_ID,strlen(KK_CCU_ID));
			INFO_PRINT("kk_cloud_key_init error\n");
			return -1;
		}
    }else{
        //_setDevice_Code(KK_CCU_ID,strlen(KK_CCU_ID));
		INFO_PRINT("kk_cloud_key_init error\n");
		return -1;
    }
	#else
    HAL_Execel_cmd(GET_KEY_CMD,(char *)key,sizeof(key),&key_len);
    if(key_len > 0 && key_len <= 128){
		memcpy(s_key,key,key_len-1);
		INFO_PRINT("s_key:%s\n",s_key);
    }else{
		return -1;
    }
	#endif
	return 0;
}
int kk_cloud_get_key(char *key)
{
	strncpy(key, s_key, strlen(s_key));
	printf("kk_cloud_get_key:%s\n",s_key);
	return strlen(s_key);
}

static int mqtt_start(void)
{
	int count = 0;
	MQTTAsync mqttClient;
	int rc = 0;
	mqttClient = KK_MQTT_Connect();
	if(mqttClient == NULL)
	{
		WARNING_PRINT("KK_MQTT_Connect FAIL!!!\n");
	}
	while(1)
	{
		usleep(100000L);
		if(kk_get_cloud_status() == 0){
			//printf("------------------------------>count:%d\n",count);
			count++;
			if(count>500)
			{
				count = 0;
				WARNING_PRINT("---------------------------------->CONNECT FAIL!!!\n");
				break;
				//INFO_PRINT("i am send now\n");
				//KK_MQTT_SendMsg(TOPIC,"hello my world",2);
			}
		}else{
			if(count > 0){
				count = 0;
			}
		}
		//INFO_PRINT(" %s \n",testStr);

	}
	INFO_PRINT("MQTTAsync_destroy\n");
	MQTTAsync_destroy(&mqttClient);
	return -1;

}
extern MQTTAsync kk_mqtt_connect();
extern MQTTAsync kk_connect_default(void);
static int mqtt_start_ex(int isdefault)
{
	int count = 0;
	MQTTAsync mqttClient;
	int rc = 0;
	if(isdefault){
		mqttClient = kk_connect_default();
	}else{
		mqttClient = kk_mqtt_connect();
	}
	if(mqttClient == NULL){
		WARNING_PRINT("KK_MQTT_Connect FAIL!!!\n");
		return -1;
	}
	while(1)
	{
		usleep(100000L);
		if(kk_get_cloud_status() == 0){
			//printf("------------------------------>count:%d\n",count);
			count++;
			if(count>500)
			{
				count = 0;
				WARNING_PRINT("---------------------------------->CONNECT FAIL!!!\n");
				break;
				//INFO_PRINT("i am send now\n");
				//KK_MQTT_SendMsg(TOPIC,"hello my world",2);
			}
		}else{
			if(count > 0){
				count = 0;
			}
		}
		//INFO_PRINT(" %s \n",testStr);

	}
	INFO_PRINT("MQTTAsync_destroy\n");
	MQTTAsync_destroy(&mqttClient);
	return -1;

}
int kk_start_ccu_register(void);
extern int kk_info_report_start(void);
extern int kk_dl_config();
extern int kk_register_auth_get();

static int setStoragePath(char* path){
	if (path == NULL){
		ERROR_PRINT("[%s] path is null !!!!!!!!!!!\n", __FUNCTION__);
		return -1;
	}

	sprintf(KK_DEVICESECRET_PATH, "%s/%s", path, KK_DEVICESECRET_PATH_SUB);
	sprintf(KK_TOKEN_PATH, "%s/%s", path, KK_TOKEN_PATH_SUB);
	sprintf(KK_DEVICE_MAP_FILE_PATH, "%s/%s", path, KK_DEVICE_MAP_FILE_PATH_SUB);
	sprintf(KK_DB_FILE, "%s/%s", path, KK_DB_FILE_SUB);
	sprintf(KK_LAN_NODE_DB_FILE, "%s/%s", path, KK_LAN_NODE_DB_FILE_SUB);
	sprintf(TSL_SUBDEVICE_PATH_FILE, "%s/%s", path, TSL_SUBDEVICE_PATH_FILE_SUB);
	sprintf(TSL_GATEWAY_PATH_FILE, "%s/%s", path, TSL_GATEWAY_PATH_FILE_SUB);
	sprintf(TSL_CCU_PATH_FILE, "%s/%s", path, TSL_CCU_PATH_FILE_SUB);
	sprintf(TSL_SCENE_PATH_FILE, "%s/%s", path, TSL_SCENE_PATH_FILE_SUB);
	sprintf(OTA_IMG_PATH, "%s/%s", path, OTA_IMG_PATH_SUB);
	sprintf(OTA_IMG_FILE, "%s/%s", path, OTA_IMG_FILE_SUB);
	sprintf(OTA_IMG_FILE_MD5, "%s/%s", path, OTA_IMG_FILE_MD5_SUB);

	sprintf(KK_CONFIG_FILE_PATH, "%s/%s", path, KK_CONFIG_FILE_PATH_SUB);
#ifdef CONFIG_A133_PLATFORM
	sprintf(KK_DEFAULT_CONFIG_FILE_PATH, "%s/%s", path, KK_DEFAULT_CONFIG_FILE_PATH_SUB);
	sprintf(KK_AUTH_CONFIG_FILE_PATH, "%s/%s", path, KK_AUTH_CONFIG_FILE_PATH_SUB);
#endif

	kk_set_storage_dir(path);
	return 0;
}


#ifdef CONFIG_NDK
int app_main(char* path)
#else
int main(int argc, char* argv[])
#endif
{
	int rc = 0;
	openlog("kcloud",LOG_PID,LOG_USER);
#ifdef CONFIG_NDK
	setStoragePath(path);
#endif
	/*set the callback to get the device date to cloud*/
	rc = KK_Ccuid_init();
	if(rc == -1){
		ERROR_PRINT("CCUID GET FAIL!!!!!!!!!!!\n");
		return 0;
	}
	kk_cloud_pid_init();
	kk_cloud_key_init();
	kk_ipc_init(IPC_APP2MID,(ipc_cb*)KK_Data_FromDev,NULL,NULL);
#if 1
	kk_dl_config();
again:
	rc = kk_register_auth_get();
	if(rc == 0){
		rc = mqtt_start_ex(0);
		if(rc < 0){
			kk_write_disconnect_flag();
			sleep(2);
			goto again;
		}
	}
	#if 0
	else if(rc == -2){
		rc = mqtt_start_ex(1);
		if(rc < 0){
			kk_write_disconnect_flag();
			sleep(2);
			goto again;
		}
	}
	#endif
	else{
		kk_write_disconnect_flag();
		sleep(2);
		goto again;
	}
#else
again:
	rc = kk_start_ccu_register();
	if(rc == 0){
		rc = mqtt_start();
		if(rc < 0){
			kk_write_disconnect_flag();
			sleep(2);
			goto again;
		}
	}else{
		kk_write_disconnect_flag();
		sleep(2);
		goto again;
	}
#endif
	return rc;
}
