

#include <stdio.h>
#include "kk_tsl_api.h"
#include "kk_sub_db.h"
#include "sqlite3.h"
#define KK_SUB_DB_FILE                                   "subDevice.db"

typedef struct {
    void *mutex;
	int  subDevNum;
    sqlite3 *pDb;	
} kk_subDb_ctx_t;

static kk_subDb_ctx_t s_kk_subDb_ctx = {NULL,0,NULL};
static kk_subDb_ctx_t *_kk_subDb_get_ctx(void)
{
    return &s_kk_subDb_ctx;
}
static void _kk_subDb_lock(void)
{
    kk_subDb_ctx_t *ctx = _kk_subDb_get_ctx();
    if (ctx->mutex) {
        HAL_MutexLock(ctx->mutex);
    }
}

static void _kk_subDb_unlock(void)
{
    kk_subDb_ctx_t *ctx = _kk_subDb_get_ctx();
    if (ctx->mutex) {
        HAL_MutexUnlock(ctx->mutex);
    }
}

static int kk_subDev_db_Init(void)
{
    kk_subDb_ctx_t *ctx = _kk_subDb_get_ctx();

    //eUtils_LockLock(&sLock);
    _kk_subDb_lock();
    
    if (sqlite3_open_v2(KK_SUB_DB_FILE, &ctx->pDb, SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE | SQLITE_OPEN_FULLMUTEX, NULL) != SQLITE_OK)
    { 
        printf("Error initialising linkage database (%s)", sqlite3_errmsg(ctx->pDb));
		_kk_subDb_unlock();
        return FAIL_RETURN; 
    }     
    printf("sub db Database opened\n");
    {
		const char *pSubDevTable = "CREATE TABLE IF NOT EXISTS SubDeviceInfo(idx INTEGER,isOnline INTEGER,deviceMac varchar(17),productId varchar(33), deviceSN varchar(33), deviceId varchar(33))";

	    char *pcErr;
        
//     DBG_vPrintf(DBG_SQL, "Execute SQL: '%s'\n", pConditionTableDef);
        
        if (sqlite3_exec(ctx->pDb, pSubDevTable, NULL, NULL, &pcErr) != SQLITE_OK)
        {
            printf("Error creating table (%s)\n", pcErr);
            sqlite3_free(pcErr);
            //eUtils_LockUnlock(&sLock);
            _kk_subDb_unlock();
            return FAIL_RETURN;
        }
	 
    }

    //eUtils_LockUnlock(&sLock);
    _kk_subDb_unlock();
    return SUCCESS_RETURN;
}
static int _kk_load_subDevice(void)
{
	const char *searchCmd = "select * from SubDeviceInfo;";	
	sqlite3_stmt *stmt;	
    kk_subDb_ctx_t *ctx = _kk_subDb_get_ctx();
	int devId;
	int res = 0;
	_kk_subDb_lock();
	sqlite3_prepare_v2(ctx->pDb, searchCmd, strlen(searchCmd), &stmt, NULL);
	printf("_kk_load_subDevice total_column = %d\n", sqlite3_column_count(stmt));	
	while(sqlite3_step(stmt) == SQLITE_ROW){
	   res = dm_mgr_subdev_create(sqlite3_column_text(stmt, 2),sqlite3_column_text(stmt, 3),sqlite3_column_text(stmt, 4),
	   					sqlite3_column_text(stmt, 5),&devId);
	   if(res != SUCCESS_RETURN){
		   printf("[%s][%d]dm_mgr_subdev_create FAIL!!!\n",__FUNCTION__,__LINE__);
	   }
	   else{
	   	   ctx->subDevNum++;
	   }
	   iotx_dm_subscribe(devId);
	   usleep(100000);
    }	
	sqlite3_finalize(stmt);
	_kk_subDb_unlock();
	return SUCCESS_RETURN;

}
int kk_subDb_init(void)
{
	int res = 0;
    kk_subDb_ctx_t *ctx = _kk_subDb_get_ctx();
	
    /* Create Mutex */
    ctx->mutex = HAL_MutexCreate();
    if (ctx->mutex == NULL) {
        return FAIL_RETURN;
    }

	res = kk_subDev_db_Init();
	if(res != SUCCESS_RETURN){
		printf("[%s][%d]kk_wlist_db_Init FAIL!!!\n",__FUNCTION__,__LINE__);

	}
	_kk_load_subDevice();
	return SUCCESS_RETURN;
}
static int _kk_check_subDev_exist(const char* device_mac)
{
	int isExist = 0;
	sqlite3_stmt *stmt;
	char *pmac = NULL;
    kk_subDb_ctx_t *ctx = _kk_subDb_get_ctx();
	const char *searchCmd = "select * from SubDeviceInfo;";	
	_kk_subDb_lock();
	sqlite3_prepare_v2(ctx->pDb, searchCmd, strlen(searchCmd), &stmt, NULL);
	printf("total_column = %d\n", sqlite3_column_count(stmt));
	while(sqlite3_step(stmt) == SQLITE_ROW){
	   pmac = sqlite3_column_text(stmt, 1);
	   if(!strcmp(device_mac,pmac))
	   
{
		 isExist = 1;
		 break;
	   }
    }
    printf("\n");
	sqlite3_finalize(stmt);
	_kk_subDb_unlock();
	return isExist;

	

}

int kk_subDev_insert_db(int isOnline,char device_mac[DEVICE_MAC_MAXLEN],char product_Id[PRODUCT_KEY_MAXLEN], \
										char device_SN[DEVICE_SN_MAXLEN],char device_Id[DEVICE_NAME_MAXLEN])
{
	const char *insertCmd = "insert into SubDeviceInfo (idx,isOnline, deviceMac, productId,deviceSN,deviceId) values ('%d','%d', '%s', '%s','%s','%s');";
	char *sqlCmd = NULL;
	int rc = 0;
	char *zErrMsg = 0;
    kk_subDb_ctx_t *ctx = _kk_subDb_get_ctx();


	if(_kk_check_subDev_exist((const char*)device_mac) == 1)
	{
		printf("[%s][%d] DATA ALREADY EXIST!!!\n",__FUNCTION__,__LINE__);
		return SUCCESS_RETURN;
	}
	_kk_subDb_lock();
	sqlCmd = sqlite3_mprintf(insertCmd,ctx->subDevNum,isOnline,device_mac,product_Id,device_SN,device_Id);	

	rc = sqlite3_exec(ctx->pDb, sqlCmd, NULL, NULL, &zErrMsg);
	if( rc != SQLITE_OK ){
	   printf("SQL error: %s\n", zErrMsg);
	   sqlite3_free(zErrMsg);
	}else{
	   printf("Table insert data successfully\n");
	}
	sqlite3_free(sqlCmd);
	ctx->subDevNum++;
	_kk_subDb_unlock();
	return SUCCESS_RETURN;
}
int kk_subDev_delete_byMac(char device_mac[DEVICE_MAC_MAXLEN])
{
	const char *deleteCmd = "delete from SubDeviceInfo where deviceMac = %s;";
	char *sqlCmd = NULL;
	int rc = 0;
	char *zErrMsg = 0;
	kk_subDb_ctx_t *ctx = _kk_subDb_get_ctx();

	_kk_subDb_lock();
	 sqlCmd = sqlite3_mprintf(deleteCmd,device_mac);	

	 printf("Table delete data sqlCmd:%s\n",sqlCmd);
	rc = sqlite3_exec(ctx->pDb, sqlCmd, NULL, NULL, &zErrMsg);
	if( rc != SQLITE_OK ){
	   printf("SQL error: %s\n", zErrMsg);
	   sqlite3_free(zErrMsg);
	}else{
	   printf("Table delete data successfully\n");
	}
	sqlite3_free(sqlCmd);
	_kk_subDb_unlock();
	return SUCCESS_RETURN;
}

int kk_subDev_update_online(int isOnline,const char *device_mac)
{
	char *sqlCmd = NULL;
	int len =0;
	int rc = 0;
	char *zErrMsg = 0;
	kk_subDb_ctx_t *ctx = _kk_subDb_get_ctx();

	_kk_subDb_lock();
	sqlCmd = sqlite3_mprintf("UPDATE SubDeviceInfo SET isOnline=%d  WHERE device_mac=%s",isOnline,device_mac);	
	printf("kk_subDev_update_online sqlCmd:%s\n",sqlCmd);
	rc = sqlite3_exec(ctx->pDb, sqlCmd, NULL, NULL, &zErrMsg);
	if( rc != SQLITE_OK ){
	   printf("SQL error: %s\n", zErrMsg);
	   sqlite3_free(zErrMsg);
	}else{
	   printf("Table updata data successfully\n");
	}
    sqlite3_free(sqlCmd);
	_kk_subDb_unlock();
	return SUCCESS_RETURN;
}


