
#include "SdLib.h"

#include <math.h>
#include <unistd.h>

#include <sstream>
#include <thread>
#include <vector>

#include "CoordSys.h"
#include "FileSys.h"
#include "Log.h"
#include "MapConfig.h"
#include "Save.h"
#include "Utils.h"

using namespace jf;

SdLib::SdLib() { a = new BindRoad(); }

void SdLib::Init(const std::string &configJsonPath) {}

bool SdLib::GetDataByWid(const Point &ingps, int wid, SdNode &out) {
    // jf_log_error("assert false : SdLib::GetDataByWid {}", wid);
    return false;
    /*
    rect r = P2R(ingps, 45, 45);
    w->LoadTileInRect(r);

    if(!w->GetNodeData(wid, out)){
      // jf_log_info("[SdLib::GetDataByWid] : GetNodeData failed {}", wid);
      return false;
    }

    w->RemoveUnsedTiles(ingps);
    return true;
    */
}

void SdLib::GetBindRoadResult(const BindRoadInput &in, BindRoadOutput &o) {
    Rect2D r = P2R(in.ingps, 45, 45);
    SdWorld::GetSingleton()->LoadTileInRect(r);

    a->BindRoadHmm({in.ingps}, o);
}

const SdNode *SdLib::GetNearestNode(const Point &ingps, const Rect2D &r, double &distance) {
    SdNodeId lValue;
    if (!SdWorld::GetSingleton()->GetNearestNodeId(ingps, r, lValue, distance)) return nullptr;
    return SdWorld::GetSingleton()->GetNodeData(lValue);
}

/*
bool SdLib::getSdNearbyPoints(
    const point &ingps,
    int prev_metre,
    int next_metre,
    std::vector<SdNode> &out,
    int &out_index)
{
  SdNode nd;
  double distance = 0;
  std::vector<SdNode> exceptions;
  if (!w->GetNearestNode(ingps, exceptions, nd, distance)) {
    // jf_log_error("[SdLib::getSdNearbyPoints]: GetNearestNode failed\n ingps:{0}, {1}, {2}, prev_metre:{3}, next_metre:{4}", ingps.lon, ingps.lat, ingps.alt, prev_metre, next_metre);
    return false;
  }
  std::vector<SdNode> next_nds;
  std::vector<SdNode> prev_nds;
  w->iterNodesByMetre(next_metre, nd, next_nds, true);
  w->iterNodesByMetre(prev_metre, nd, prev_nds, false);
  // 因为向前找的第一个点和向后找的第一个点是重复的，所以需要删除其中一个
  if(next_nds.size() >= 1 && prev_nds.size() >= 1 && next_nds[0].p == prev_nds[0].p){
    next_nds.erase(next_nds.begin());
  }
  std::reverse(prev_nds.begin(), prev_nds.end());
  out_index = prev_nds.size() - 1;
  prev_nds.insert(prev_nds.end(), next_nds.begin(), next_nds.end());
  out = prev_nds;
  if(out.size() == 1){
    // jf_log_error("[SdLib::getSdNearbyPoints]:only 1 node return, so get nearby failed");
    return false;
  }else {
    // jf_log_info("[SdLib::getSdNearbyPoints]:success, size:{}", out.size());
    return true;
  }
}
*/

// std::vector<Point> SdLib::LoadGpses() { return sdworld::GetSingleton()->GetSave()->LoadGpses(); }
