/****************************************************************************
** File name    :  HTInitUtils.cpp
** Description  :  Defines service initialization API
** Create date  :  2018.09.01
** Auther by    :  Liuyx
** Version info :  V1.0.01
** Copyright (C) 2002-2018 xi'an huatek, Inc Co., Ltd
** Update record:  
** DATE         AUTHER   DESC 
** -------------------------------------------------------------------------               
** 2018.09.01   Liuyx    first build
****************************************************************************/
#include "HTGlobal.h"
#include "HTInitUtils.h"

static const char *_FILE_ = "HTInitUtils.cpp" ;

// make and get a globle seq number
int get_seqno(void)
{
    int iseq = 0;
    mutex_lock(g_seq_mutex);
    iseq = ++g_seqno ;
    if(g_seqno >= 255 ) 
	g_seqno = 0;
    mutex_unlock(g_seq_mutex);
    return iseq;
}

int loadServiceEvent()
{
    // 初始化日志共享资源锁
    vInitLogMutex();                                 // 初始化log文件锁与句柄
    vPrtLogMsg(LOG_DEBUG, 0, "***********************************************************************");
    mutex_create(g_seq_mutex); 
    mutex_create(g_ied_mutex);
    mutex_create(g_list_comtrad_files_mutex);
    mutex_create(g_thres_conf_mutex);
    mutex_create(g_MapIedConn_mutex);
    mutex_create(g_map_device_mutex);
    mutex_create(g_ctrl_conf_mutex);
    mutex_create(g_map_parambind_mutex);
    mutex_create(g_list_db_body_mutex);
    mutex_create(g_list_db_warn_mutex);
    g_Running = 1 ;                                  // 服务启动标志
    g_TConfig.getIniConfig();
    if(!CDBMySQL::Instance()->dbConnectPool()) {
        vFreeLogMutex();                            // 释放log文件锁与句柄
        mutex_close(g_seq_mutex);
        mutex_close(g_thres_conf_mutex);
        mutex_close(g_MapIedConn_mutex);
        mutex_close(g_map_device_mutex);
        mutex_close(g_ctrl_conf_mutex);
        mutex_close(g_ctrl_conf_mutex);
        mutex_close(g_map_parambind_mutex);
        mutex_close(g_ied_mutex); 
        mutex_close(g_list_db_body_mutex);
        mutex_close(g_list_db_warn_mutex);
        g_Running = 0 ;
        return RET_FAIL;
    }
    vLoadCommunicationConf(); // 加载通信参数
    return RET_OK;
}

// 重新从数据库加载配置
void reloadServiceEvent(int platform_id)
{
    //TDatabase* g_TDatabase = NULL;
    //g_TDatabase = TDatabase::Instance();
}

int unLoadServiceEvent()
{
    CDBMySQL::Instance()->dbFreeConnectPool();
    g_Running = 0 ;
    HTFreeThreadHandle();

    // 释放日志共享资源锁
    mutex_close(g_seq_mutex);
    mutex_close(g_MapIedConn_mutex);
    mutex_close(g_thres_conf_mutex);
    mutex_close(g_map_device_mutex);
    mutex_close(g_ctrl_conf_mutex);
    mutex_close(g_list_comtrad_files_mutex);
    mutex_close(g_map_parambind_mutex);
    mutex_close(g_ied_mutex);
    mutex_close(g_list_db_body_mutex);
    mutex_close(g_list_db_warn_mutex);
    vFreeLogMutex();
    return RET_OK;
}



