#include <stdio.h>
#include <string.h>
#include <math.h>
#include "ant.h"
#include "db_api/CDBSingletonDefine.h"
#include "event.h"
template<> std::shared_ptr<sit_list> 
single_base<sit_list, int, std::shared_ptr<site>>::m_instance=std::make_shared<sit_list>();
int site::index()const
{
	return m_algo+(m_num_dims<<1);
}

site::site(int id)
	:m_algo(0)
	,m_num_dims(0)
    ,m_id(id)
    ,m_path_empty(true)
{
	m_time=time(0);
}
const algo_config&site::config()const
{
	return g_config[index()];
}
bool visit_site_status::visit(std::shared_ptr<site> s)
{
	time_t now = time(0);
	int diff = now - s->m_time;
	if(diff > READER_TIMEOUT)	
	{
        auto ev_ptr = event_list::instance()->get_event_reader(s->m_id,ET_READER_ERROR);
		if(!ev_ptr)
		{
			auto ev_ptr = event_list::create_event_reader(s->m_id,ET_READER_ERROR);
            event_list::copy_event(s, ev_ptr);
            ev_ptr->m_limit_value = READER_TIMEOUT;
            ev_ptr->m_cur_value = diff;
            //保存到数据库
            event_list::save_event(ev_ptr);
			event_list::instance()->add(ev_ptr->get_list_id(),ev_ptr);
			log_info("reader_error_create: %d,diff:%d",s->m_id,diff);
		}
	}
	else
	{
        auto ev_ptr = event_list::instance()->get_event_reader(s->m_id,ET_READER_ERROR);
        if(ev_ptr && !ev_ptr->is_end())
		{
			event_list::copy_event(s, ev_ptr);
			ev_ptr->m_cur_value = diff;
			ev_ptr->m_status = ES_END;
            //保存到数据库
            event_list::save_event(ev_ptr);
			log_info("reader_error_delete: %d,diff:%d",s->m_id,diff);
		}
	}
	return true;
}
void sit_list::read_ant_path(int id)
{
     std::string sql = "SELECT reader_id,tof_flag,b_x,b_y,b_z,e_x,e_y,e_z,spacing_ratio FROM dat_reader_path_tof_n";

     if(-1 == id)
     {
         sql.append(";");
     }
     else
     {
         sql.append(" AND reader_id=");
         sql.append(std::to_string(id));
         sql.append(";");

         std_debug("修改path sql=%s", sql.c_str());
         log_info("修改path sql=%s", sql.c_str());
     }

     std::string Error;
     YADB::CDBResultSet DBRes;
     sDBConnPool.Query(sql.c_str(),DBRes,Error);
     int nCount = DBRes.GetRecordCount( Error );
     if (nCount < 1)
     {
         log_error("修改path失败，数据库中找不到(dat_reader_path_tof_n): 分站id=%d", id);
         return ;
     }

     while ( DBRes.GetNextRecod(Error) )
     {
         int reader_id  = 0;
         DBRes.GetField( "reader_id",reader_id, Error );

         auto site_ptr=sit_list::instance()->get(reader_id);
         if(nullptr==site_ptr)
             continue;

         int pid=0;
         DBRes.GetField( "tof_flag",pid, Error );

         double b_x= 0;
         DBRes.GetField( "b_x",b_x, Error );

         double b_y= 0;
         DBRes.GetField( "b_y",b_y, Error );

         double b_z= 0;
         DBRes.GetField( "b_z",b_z, Error );

         double e_x= 0;
         DBRes.GetField( "e_x",e_x, Error );

         double e_y= 0;
         DBRes.GetField( "e_y",e_y, Error );

         double e_z= 0;
         DBRes.GetField( "e_z",e_z, Error );

         double spacing_ratio = 0;
         DBRes.GetField( "spacing_ratio",spacing_ratio, Error );
         log_info("ant_path:%d,%.2f,%.2f,%.2f,%.2f",reader_id,b_x,b_y,e_x,e_y);
         point p1(b_x,-b_y);
         point p2(e_x,-e_y);
         auto &sit_ = *site_ptr;
         if(-1!=id)//清空path
         {
            sit_.clear_path();
            log_info( "修改path 清空path，分站id=%d\n", id );
            std_debug( "修改path 清空path，分站id=%d\n", id );
         }

         if(pid == 0)
         {
             line_v l(p1,p2);
             {
                 point px = l.line::projection(sit_);
                 sit_.set(px);
                 for(int i=0;i<2;i++)
                 {
                     path p;
                     p.m_slope[0] = spacing_ratio;
                     p.m_line[0] = line_v(px,l[i]);
                     sit_.m_ant[i].m_path.push_back(p);
                 }
             }
         }
         else
         {
             ant &a = pid<0?sit_.m_ant[0]:sit_.m_ant[1];
             if(a.m_path.size()!=0)
             {
                 path &p = a.m_path[0];
                 p.m_line[abs(pid)-1] = line_v(p1,p2);
                 p.m_slope[abs(pid)-1] = spacing_ratio;
             }
             else
             {
                 path p;
                 p.m_line[abs(pid)-1] = line_v(p1,p2);
                 p.m_slope[abs(pid)-1] = spacing_ratio;
                 a.m_path.push_back(p);
             }
             if(abs(pid)==1)
                 sit_.set(p1);
         }
     }

     if(-1==id)
     {
         log_info( "read_ant_path. The record count=%ld\n", nCount );
         for(auto&_s:sit_list::instance()->m_map)
         {
             _s.second->deal_path();
         }
     }
     else
     {
         auto sit_ptr=sit_list::instance()->get(id);
         if(sit_ptr)
         {
             sit_ptr->deal_path();
             log_info( "修改path成功，分站id=%d\n", id );
             std_debug( "修改path成功，分站id=%d\n", id );
         }
     }
}

void sit_list::init_site(int id)
{
     std::string sql = "SELECT reader_id, reader_type_id, dat_reader.map_id, \
             area_id, device_type_id, dimension, dat_map.scale\
             FROM dat_reader, dat_map where \
             dat_reader.map_id=dat_map.map_id and state=0";

     if(-1 == id)
     {
         sql.append(";");
     }
     else
     {
         sql.append(" AND reader_id=");
         sql.append(std::to_string(id));
         sql.append(";");

         std_debug("增加或修改分站 sql=%s", sql.c_str());
         log_info("增加或修改分站 sql=%s", sql.c_str());
     }

     std::string Error;
     YADB::CDBResultSet DBRes;
     sDBConnPool.Query(sql.c_str(),DBRes,Error);
     int nCount = DBRes.GetRecordCount( Error );
     if (nCount < 1)
     {
         log_error("增加或修改失败，数据库中找不到: 分站id=%d", id);
         return ;
     }

     log_info( "增加或修改 init_site. The record count=%ld\n", nCount );

     while ( DBRes.GetNextRecod(Error) )
     {
         int reader_id  = 0;
         DBRes.GetField( "reader_id",reader_id, Error );

         auto site_ptr=sit_list::instance()->get(reader_id);
         if(nullptr==site_ptr)
         {
             site_ptr = std::make_shared<site>(reader_id);
             sit_list::instance()->add(reader_id,site_ptr);
         }

         int reader_type_id  = 0;
         DBRes.GetField( "reader_type_id",reader_type_id, Error );

         int map_id  = 0;
         DBRes.GetField( "map_id",map_id, Error );

         int area_id  = 0;
         DBRes.GetField( "area_id",area_id, Error );

         int device_type_id  = 0;
         DBRes.GetField( "device_type_id",device_type_id, Error );

         int dimension  = 0;
         DBRes.GetField( "dimension",dimension, Error );

         double scale= 0;
         DBRes.GetField( "scale",scale, Error );

         site_ptr->m_reader_type_id = reader_type_id;
         site_ptr->m_map_id = map_id;
         site_ptr->m_area_id = area_id;

         site_ptr->m_device_type_id = device_type_id;

         site_ptr->m_dimension = dimension;
         site_ptr->m_scale = scale;
     }
}

void sit_list::read_sit_list(int id)
{
    std::string sql = "SELECT antenna_id, a.reader_id, idx, a.x, a.y, a.z, a.angle \
            FROM dat_antenna a, dat_reader r \
            WHERE a.reader_id = r.reader_id";

    if(-1 == id)
    {
        sql.append(";");
    }
    else
    {
        sql.append(" AND antenna_id=");
        sql.append(std::to_string(id));
        sql.append(";");

        std_debug("基础数据 增加或修改天线 sql=%s", sql.c_str());
        log_info("基础数据 增加或修改天线 sql=%s", sql.c_str());
    }

    std::string Error;
    YADB::CDBResultSet DBRes;
    sDBConnPool.Query(sql.c_str(),DBRes,Error);
    int nCount = DBRes.GetRecordCount( Error );
    if (nCount < 1)
    {
        log_error("基础数据 增加或修改失败，数据库中找不到: 天线id=%d", id);
        return ;
    }

    std::unordered_map<int,std::shared_ptr<site>> map;
    while ( DBRes.GetNextRecod(Error) )
    {
        int antenna_id = 0;
        DBRes.GetField( "antenna_id",antenna_id, Error );

        int reader_id  = 0;
        DBRes.GetField( "reader_id",reader_id, Error );

        int idx=0;
        DBRes.GetField( "idx",idx, Error );

        int antid = idx-1;
        if(antid >= 2)
          continue;

        double x= 0;
        DBRes.GetField( "x",x, Error );

        double y= 0;
        DBRes.GetField( "y",y, Error );

        double z= 0;
        DBRes.GetField( "z",z, Error );

        if(-1 == id)
        {
            std::shared_ptr<site> site_ptr=nullptr;
            auto it = map.find(reader_id);
            if(it==map.end())
            {
                site_ptr = std::make_shared<site>(reader_id);
                map.insert({reader_id,site_ptr});
            }
            else
              site_ptr=it->second;
            site_ptr->m_ant[antid].m_id = antenna_id;
            site_ptr->m_ant[antid].set(x,-y);
            log_info("reand_ant..%d,%d,%.2f,%.2f",reader_id,antid,x,y);
        }
        else
        {
            auto site_ptr = sit_list::instance()->get(reader_id);
            if(site_ptr)
            {
                site_ptr->m_ant[antid].set(x,-y);

                site_ptr->set_ex();
            }

            log_info("基础数据 增加或修改天线成功：天线id:%d,分站id:%d",id,reader_id);
            std_debug("基础数据 增加或修改天线成功：天线id:%d,分站id:%d",id,reader_id);
        }
    }

    if(-1 == id)
    {
        log_info( "init_antenna. The record count=%ld\n", nCount );
        sit_list::instance()->add(map);
        for(auto&sit_:map)
        {
            sit_.second->set_ex();
        }
    }
}
#if 0
void sit_list::init_site()
{
    const char *sql = "SELECT reader_id, reader_type_id, dat_reader.map_id, \
            area_id, device_type_id, dimension, dat_map.scale\
            FROM dat_reader, dat_map where \
            dat_reader.map_id=dat_map.map_id and state=0;";

    std::string Error;
    YADB::CDBResultSet DBRes;
    sDBConnPool.Query(sql,DBRes,Error);
    uint64_t nCount = DBRes.GetRecordCount( Error );
    if (nCount > 0)
    {
        log_info( "init_site. The record count=%ld\n", nCount );

        while ( DBRes.GetNextRecod(Error) )
        {
            int reader_id  = 0;
            DBRes.GetField( "reader_id",reader_id, Error );

            auto site_ptr=sit_list::instance()->get(reader_id);
            if(nullptr==site_ptr)
            {
                site_ptr = std::make_shared<site>(reader_id);
                sit_list::instance()->add(reader_id,site_ptr);
            }

            int reader_type_id  = 0;
            DBRes.GetField( "reader_type_id",reader_type_id, Error );

            int map_id  = 0;
            DBRes.GetField( "map_id",map_id, Error );

            int area_id  = 0;
            DBRes.GetField( "area_id",area_id, Error );

            int device_type_id  = 0;
            DBRes.GetField( "device_type_id",device_type_id, Error );

            int dimension  = 0;
            DBRes.GetField( "dimension",dimension, Error );

            double scale= 0;
            DBRes.GetField( "scale",scale, Error );

            site_ptr->m_reader_type_id = reader_type_id;
            site_ptr->m_map_id = map_id;
            site_ptr->m_area_id = area_id;

            site_ptr->m_device_type_id = device_type_id;

            site_ptr->m_dimension = dimension;
            site_ptr->m_scale = scale;
        }
    }
}
#endif
algo_config site::g_config[]=
{
	{ "tof-1",  1, 2, 0.1, 1 },
	{ "tdoa-1", 2, 2, 0.1, 1 },
	{ "tof-2",  2, 3, 0.1, 1 },
	{ "tdoa-2", 3, 3, 0.1, 1 },
	{ "tof-3",  3, 4, 0.1, 1 },
	{ "tdoa-3", 4, 4, 0.1, 1 }
};

#ifdef _TEST
int main()
{
	log_init("./log.ini");
    //sit_list *sl = sit_list::instance();
	sit_list::instance()->load("data_reader_antenna.txt","path_tof.txt");
	sit_list::instance()->get(209)->solving(0,100);
	sit_list::instance()->get(209)->solving(1,100.5);
    //std_info("---%d",(*sl)[209].m_ant[0].m_path.size());
    //std_info("---%d",(*sl)[209][0].size());
    //std_info("---%s",(*sl)[209][0][0][0].to_string().c_str());
}
#endif
