#include <ev++.h>
#include <log.h>
#include <net-service.h>
#include "db_api/CDBConnPool.h"
#include "websocket/wsClientMgr.h"
#include "websocket/wsTimerThread.h"

#include "card.h"
#include "ant.h"
#include "card_path.h"

#include <config_file.h>

config_file config;
struct Init_Setting
{
	void init()
	{
		std::string url=config.get("service.websocket_url","ws://127.0.0.1:8086");
		int32_t send_interval =config.get("service.interval_send_json_postion",1000);
		std_info("json_interval:%d",send_interval);
		std::vector<std::string> url_list;
		url_list.push_back(url);
		wsClientMgr_init(url_list,send_interval);//init websocket

		YADB::_DB_POOL_SETTING_ DBSetting;

		DBSetting.Host = config.get("db.host","");
		DBSetting.User = config.get("db.user","root");
		DBSetting.PWD = config.get("db.passwd","");
		DBSetting.DBName = config.get("db.dbname","yaxt");
		DBSetting.CharSet = config.get("db.charset","utf-8");
		DBSetting.TimeOut = config.get("db.conn_timeout",5);
		DBSetting.PoolSize = config.get("db.conn_timeout",30);
		_mysql_init(DBSetting);

		sit_list::instance()->load_from_db();

		card_list::instance()->init_card_from_db();
	}

	void _mysql_init(YADB::_DB_POOL_SETTING_ &dps)
	{
		std::string Error;
	
		//创建连接池
		if ( !sDBConnPool.Create( dps, Error ) )
		{
			log_error("数据库线程池创建失败,Err=%s\n", Error.c_str());
		}
	}

	void wsClientMgr_init(const std::vector<std::string>&uri_list,int32_t st)
	{
		std::map<std::string, YA::MSG_HANDLE_FUNC_TYPE> MsgFuncList;
	
		//MsgFuncList.insert( std::make_pair( "req_all_data", On_req_all_data ) );
		//MsgFuncList.insert( std::make_pair( "req_all_person_on_car", On_req_all_person_on_car ) );
	
		swsClientMgr.Build( uri_list, MsgFuncList );
	
		//连接服务器
		if ( swsClientMgr.connect() != 0 )
		{
			log_error("web socket init failed.");
			std_error("web socket init failed.");
			return;
		}
	
		//登录
		swsClientMgr.login();
		//init thread...
		YA::_THREAD_CONFIG_ Config;
		Config.SendInterval = st;
		swsTimerThrd.Init( Config );
		swsTimerThrd.Start();
	}
	
};


void cleanup() 
{ 
	ev_loop_destroy(ev_default_loop());
}

int main()
{
	log_init("../etc/log.ini");
	if(config.open("../etc/config.ini"))
		return -1;
	Init_Setting is;
	is.init();
	
	atexit(&cleanup);

	card_path::init();
	net_service mh;

	int port=config.get("service.port",4000);
	service_handle::instance(&mh)->run(port);

	return 0;
}

