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

#include "card.h"
#include "ant.h"
#include "area.h"
#include "card_path.h"
#include "landmark.h"
#include "special_area.h"
#include "mine.h"
#include "ya_event.h"
#include"module_service/module_area.h"
#include"module_service/module_mgr.h"

#include <config_file.h>
#include "three_rates.h"
#include "mine_business.h"
#include "main_test.h"
#include "ya_setting.h"

config_file config;
static void handlereader(uint32_t readerid,bool duration,uint32_t t)
{

}
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",1);
        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","127.0.0.1");
        DBSetting.User = config.get("db.user","root");
        DBSetting.PWD = config.get("db.passwd","123456");
        DBSetting.DBName = config.get("db.dbname","yaxt");
        DBSetting.CharSet = config.get("db.charset","utf8");
        DBSetting.TimeOut = config.get("db.conn_timeout",5);
        DBSetting.PoolSize = config.get("db.pool_size",30);
        _mysql_init(DBSetting);

		CYaSetting::Init_sys_setting();

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

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

        std_info("here....");
        area_list::instance()->init_from_db();
        std_info("here....");
	
        Landmark_list::instance()->init_from_db();

        //auto a = Landmark_list::instance()->get(5,id,pt);
        //std_info("test landmark:id:%d,dir:%d,dis:%.2f",std::get<0>(a),std::get<1>(a),std::get<2>(a));
        special_area_list::instance()->init_from_db();
        //auto s = special_area_list::instance()->get_special_id(1013,point(4727,-254),2);
        //std_info("test special_area:%d",s);
		mine_business::inst()->load();

        card_list::instance()->load_his_card_postion_from_db();
        event_list::instance()->load_his_data_from_db();
		
        db_para dp;	
        dp.Host=DBSetting.Host;
        dp.User=DBSetting.User;
        dp.PWD=DBSetting.PWD ;
        dp.DBName=DBSetting.DBName;
        dp.CharSet=DBSetting.CharSet ;
        dp.TimeOut=DBSetting.TimeOut;
        dp.PoolSize=DBSetting.PoolSize;
		init_three_rates(dp);

        printf("Init_Setting::init  Success. \n" );
    }
	void init_three_rates(const db_para& dbs)
	{
		std_info("three_rates ...................");
		init_para ip;
		ip.send_pt = handlereader;
		three_rates::get_instance()->init(ip,dbs);
		three_rates::get_instance()->start();
	}
    void _mysql_init(YADB::_DB_POOL_SETTING_ &dps)
    {
        std::string szError = "";
		//std::this_thread::sleep_for(std::chrono::seconds(2));
        //创建连接池
        if ( !sDBConnPool.Create( dps, szError ) )
        {
            log_error("数据库线程池创建失败,Err=%s\n", szError.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 ) );

        module_mgr::init(config, MsgFuncList);

        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()
{
    module_mgr::stop();
}

void usage(char ** argv)
{
    std::string cmd(argv[1]);
    if(cmd=="--help" || cmd == "-H")
    {
        printf("用法：yals [选项]文件...\n");
        printf("选项：\n");
        printf("--help				显示此帮助说明\n");
        printf("-v|--version		显示采集程序版本信息\n");
    }
    else if(cmd == "--version" || cmd == "-v")
    {
        printf("yals (采集程序) 0.1.0\n");
    }
    else
    {
        printf("Unknown option:%s\n",cmd.c_str());
        printf( "usage:yals [--version][--help][-v][-H]\n");
    }


}

int main(int argc ,char * argv[])
{
    if(argc >1)
    {
        usage(argv);
        return 0;
    }

    log_init("../etc/log.ini");
    if(config.open("../etc/config.ini"))
        return -1;
    Init_Setting is;
    is.init();

	card_path::init();
	test_find_path(point(4600,-75),point(4727,-90));

    module_mgr::start();
    atexit(&cleanup);

    printf("\nservice_handle::instance(&mh)->run(%d); \n",4000);
    net_service mh;
    int port=config.get("service.port",4000);
    service_handle::instance(&mh)->run(port);
    
    sDBConnPool.Close();

    sleep(1);
    printf("YA-SERV Server Exit ...\n");

    return 0;
}
