/*******************************************************************************
 * 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 <syslog.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

#include "com_api.h"
#include "kk_product.h"
#include "kk_findccu_handle.h"
#include "kk_login_handle.h"
#include "kk_data_handle.h"

//#include "kk_lan_queue.h"
#include "kk_lan_node_db.h"
#include "kk_lan_voice_panel.h"
#include "kk_data_mng.h"
#include "kk_lan_debug.h"
extern char * _kk_data_create(char *msgtype,const char *productCode,const char *deviceCode,const char *param);
extern int HAL_Execel_cmd(char * cmd,char * buf,int buf_len,int* ret_len);

static char s_ccuid[DEVICE_CODE_LEN] = {0};
int kk_lan_get_ccuid(_OU_ char *device_code)
{
	strncpy(device_code, s_ccuid, strlen(s_ccuid));
	printf("kk_lan_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);
	printf("_setDevice_Code:%s\n",device_code);
	strncpy(s_ccuid, device_code, len);
	return len;
}
char s_pid[PRODUCT_CODE_LEN] = {0};
static int kk_lan_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_lan_get_pid(_OU_ char *productId)
{
	strncpy(productId, s_pid, strlen(s_pid));
	printf("kk_lan_get_ccuid:%s\n",s_pid);
	return strlen(s_pid);
}

static void kk_lan_ccuid_init(void)
{
#ifdef CONFIG_A133_PLATFORM
    uint8_t data[128] = {0};
    int data_len = 0;
	uint8_t uuid[32] = {0};
	char *pstart = NULL;
	char *pEnd = NULL;
    HAL_Execel_cmd(GET_CCUID_CMD,(char *)data,sizeof(data),&data_len);
    printf("GET_CCUID_CMD:%s\n",data);
    if(data_len > 0 && data_len <= 128){
		pstart = data;
		pEnd = strstr(data,"-");
		if(pstart != NULL && pEnd != NULL){
			memcpy(uuid,pstart,pEnd-pstart);
			_setDevice_Code(uuid,pEnd-pstart);
		}else{
        	return;
		}
    }else{
        return ;
    }
#else
    uint8_t ccuid[DEVICE_CODE_LEN] = {0};
	uint8_t ccuidTmp[DEVICE_CODE_LEN] = {0};
    int ccuid_len = 0;
    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((char *)ccuidTmp,"CCU_%s",ccuid);
        _setDevice_Code((char *)ccuidTmp,strlen((char *)ccuidTmp)-1);
    }else{
        //_setDevice_Code(KK_CCU_ID,strlen(KK_CCU_ID));
    }
#endif
}

#define SYNC_INFO_FLAG				0x01
#define SYNC_INFO_PUSH_FLAG 		0x02
static int g_sync_flag;

void kk_sync_info(void)
{
	if(g_sync_flag&SYNC_INFO_FLAG){
		debug_log(LOG_CRIT_LEVEL,"[SYNC INFO] delay.\n");
	}
	g_sync_flag|=SYNC_INFO_FLAG;
}
void kk_sync_info_push(void)
{
	if(g_sync_flag&SYNC_INFO_PUSH_FLAG){
		debug_log(LOG_CRIT_LEVEL,"[SYNC INFO PUSH] delay.\n");
	}
	g_sync_flag|=SYNC_INFO_PUSH_FLAG;
}


void handler(int signum)
{
	debug_log(LOG_CRIT_LEVEL,"[sig]---------------------->signum=%d\n",signum);
	if(signum!=17 &&signum!=SIGALRM){
		exit(-1);
	}
}

void kk_sync_timer_start(void)
{
	struct itimerval timer;
	timer.it_value.tv_sec = 30;
	timer.it_value.tv_usec = 0;
	timer.it_interval.tv_sec = 0;
	timer.it_interval.tv_usec = 0;
	if(setitimer(ITIMER_REAL, &timer, NULL)<0){
		debug_log(LOG_ALERT_LEVEL,"err.\n");
	};
}


int kk_sync_timer_is_running(void)
{
	struct itimerval timer;
	getitimer(ITIMER_REAL,&timer);
	if(timer.it_value.tv_sec!=0||timer.it_value.tv_usec!=0){
		return 1;
	}
	return 0;
}


#ifdef CONFIG_NDK
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;
}
#endif

#ifdef CONFIG_NDK
int lan_main(char* path)
#else
int main(int argc, char* argv[])
#endif
{
	int ret = 0;

	struct sigaction sa;
	signal(SIGPIPE, SIG_IGN);
	signal(SIGALRM, SIG_IGN);
	signal(SIGSTOP, SIG_IGN);

	openlog("kk_lan",LOG_CONS|LOG_PID,LOG_USER);
#ifdef CONFIG_NDK
	setStoragePath(path);
#endif
	kk_lan_pid_init();
	kk_lan_ccuid_init();

	/*set the callback to get the device date to cloud*/
	kk_ipc_init(IPC_APP2MID,(ipc_cb*)KK_Data_FromMid,NULL,NULL);
	kk_findccu_handle_init();
	kk_map_dev_init();
	kk_login_init();

	#ifdef VOICE_SUPPORT
	kk_voice_panel_init(argc,argv);
	#endif

	//lan_queue_init();
	kk_lan_db_node_init();
	//kk_handle_sync_info();


	while(1){
		if(kk_sync_timer_is_running()==0&&g_sync_flag!=0){
			char *send_data = NULL;

			if(g_sync_flag&SYNC_INFO_FLAG){
				DEBUG_PRINT("[SYNC INFO].\n");

				send_data = _kk_data_create(SYNC_MSG_TYPE,"*","*","*");
				g_sync_flag&=~SYNC_INFO_FLAG;
			}else if(g_sync_flag&SYNC_INFO_PUSH_FLAG){
				DEBUG_PRINT("[SYNC INFO PUSH].\n");

				send_data  = _kk_data_create(SYNCPUSH_MSG_TYPE,"*","*","*");
				kk_handle_sync_push_info();
				g_sync_flag&=~SYNC_INFO_PUSH_FLAG;
			}else{
				g_sync_flag = 0;
				DEBUG_PRINT("err\n");
			}

			if(send_data != NULL){
				kk_ipc_send(IPC_APP2MID, send_data, strlen(send_data)+1);
				kk_sync_timer_start();
				free(send_data);
			}

		}

		usleep(100*1000);
	}
	return 0;
}

