#ifndef MLAT_H
#define MLAT_H
#include "../../../../../core_library/Core/Core/Base/JSON.h"
#include "../../../../../core_library/Core/Core/system/export.h"
#include "../global_include.h"
#include <atomic>
#include <string>

class Global;
#pragma pack(push, 8)
extern "C" {
    struct MLAT_Data {
        char icao[6];
        double lon;
        double lat;
    };
}
#pragma pack(pop)


struct MLAT_Store {
    MLAT_Data d{};
    [[nodiscard]] Psc::JSON to_json() const {
        Psc::JSON ret = Psc::JSON::object();
        ret.append({"icao", std::string(d.icao, 6)});
        ret.append({"lon", d.lon});
        ret.append({"lat", d.lat});
        return ret;
    }
    [[nodiscard]] std::string icao() const {
        return {d.icao, 6};
    }
};

struct Base_MLAT_Data {
    MLAT_Data mlat_data;
    std::string msg;
    std::string hex;
    std::string icao;
};

extern std::multimap<std::string, Base_MLAT_Data> hex_mlat_map;

struct MLAT_Config {
    std::atomic<bool> enable{};
    std::atomic<bool> merge{};
    std::string library_path;
    std::string function_name;
    ~MLAT_Config() = default;
    MLAT_Config();
    [[nodiscard]] Psc::JSON to_json() const {
        Psc::JSON ret = Psc::JSON::object();
        ret.append(Psc::JSON("enable", this->enable));
        ret.append(Psc::JSON("merge", this->merge));
        Ret_J(library_path)
        Ret_J(function_name)
        return ret;
    }
    void* lib{};
    using Func_Type = void(*)(MLAT_Data* buf, std::uint16_t* len);
    Func_Type read_func_ptr{};
    void init(const Psc::JSON* that_json);
    MLAT_Data buf[std::numeric_limits<std::uint16_t>::max()]{};
    void refresh();

    Psc::JSON get_reset() {
        std::lock_guard guard(mtx);
        Psc::JSON ret = Psc::JSON::array();
        for (auto & t : update_map) {
            ret.append(t.second.to_json());
        }
        update_map.clear();
        return ret;
    }
    void server(Global* g);
protected:
    std::mutex mtx;
    std::map<std::string, MLAT_Store> update_map;
};
#endif
