#include "MapPreApp.h"

#include <malloc.h>
#include <pthread.h>

#include <iostream>

#include "AdasMapParser.h"
#include "HdImporter.h"
#include "HdTypes.h"
#include "MapConfig.h"
#include "MapParser.h"
#include "SdId2HdId.h"
#include "SdImporter.h"
#include "SdTypes.h"
#include "World.h"

using namespace jf;

void MapPreApp::Run(const std::string &projectDir, const std::string &configJsonPath) {
    MapConfig::Init(projectDir, configJsonPath);

    // jf_log_error("{0}", MapConfig::map_use_type.c_str());

    if (0 == MapConfig::map_use_type.compare("hd")) {
        SdWorld sw = SdWorld::GetSingleton();
        HdWorld hw = HdWorld::GetSingleton();
        SdSave *ss = new SdSave;
        HdSave *hs = new HdSave;
        ss->CleanTileFile<SdTile>();
        hs->CleanTileFile<HdTile>();

        SdImporter *si = new SdImporter();
        HdImporter *hi = new HdImporter();

        MapParser *p = new MapParser;

        HdJson hd_link_data = p->Parse(MapConfig::map_file_dir, si->GetNodeCallback(), si->GetWayCallback(), si->GetBoundCallback(), si->GetRelationCallback());

        hi->Import(hd_link_data);

        sw->SerializeAll();
        hw->SerializeAll();

        const std::map<TileId, std::shared_ptr<HdTile>> &hdtiles = HdWorld::GetSingleton()->GetTiles();
        for (auto &tileIter : hdtiles) {
            auto &tid = tileIter.first;
            auto &t = tileIter.second;
            for (const auto &nodeIter : t->GetNodes()) {
                auto &hdlkid = nodeIter.first;
                auto &hdlk = nodeIter.second;
                SdId2HdId::Put(hdlkid.lValue, hdlkid);
            }
        }
        SdId2HdId::Deserialize();
    } else if (0 == MapConfig::map_use_type.compare("adas")) {
        using namespace adas;

        SdWorld sw = SdWorld::GetSingleton();
        SdSave *ss = new SdSave;
        ss->CleanTileFile<SdTile>();

        SdImporter *si = new SdImporter();

        AdasMapParser *p = new AdasMapParser;

        p->Parse(MapConfig::map_file_dir, si->GetNodeCallback(), si->GetWayCallback(), si->GetBoundCallback(), si->GetRelationCallback());

        sw->SerializeAll();
    }
}
#ifdef STANDALONE
int main(int argc, char **argv) {
    // assert(argc == 3);
    MapPreApp app;
    std::string projectDir = "/home/muyusheng/jika_ws/src/mapbox/localization/map/submodules/jfxmap/";
    std::string configJsonDir = "./maps/lingshu/mapconfig.json";
    app.Run(projectDir, configJsonDir);
    return 0;
}

#endif