#include "Base_Station.h"

namespace SSR
{
    struct HULC_Status_Message;
}

double Base_Station::theoretical_detection_range_meters(double base_height_meters, double target_height_meters)
{
    return static_cast<double>(SSR::CPR::radio_line_of_sight_range_meters(base_height_meters, target_height_meters));
}

std::optional<SSR::Position_3D> Base_Station::get_pos()
{
    std::lock_guard g(mtx);
    if (!hulc.GPS_has_valid_fix())
    {
        return std::nullopt;
    }
    return SSR::Position_3D{hulc.get_latitude(), hulc.get_longitude(), static_cast<SSR::CPR::D>(hulc.Alt)};
}

bool Base_Station::has_valid_position()
{
    std::lock_guard g(mtx);
    return hulc.GPS_has_valid_fix();
}

void Base_Station::set_msg(const SSR::HULC_Status_Message& msg)
{
    std::lock_guard g(mtx);
    hulc = msg;
    if (handle_when_updated)
        handle_when_updated(msg);
}

std::string Base_Station::to_string()
{
    std::lock_guard g(mtx);
    return "BaseStation:[" + std::to_string(hulc.get_latitude()) + ", " + std::to_string(hulc.get_longitude()) + "]";
}

Psc::JSON Base_Station::to_Json()
{
    std::lock_guard g(mtx);
    auto ret = Psc::JSON::object();
    ret.append({"序列号", hulc.SerNum});
    ret.append({"状态标志", hulc.Flags});
    ret.append({"内部使用", hulc.I_U_});
    ret.append({"时间", Psc::utc_2_local_time(hulc.xTime)});
    ret.append({"卫星数量", hulc.Sat});
    ret.append({"HDOP", hulc.get_HDOP()});
    ret.append({"GPS设备检测到", hulc.GPS_device_detected()});
    ret.append({"GPS有效", hulc.GPS_valid()});
    ret.append({"GPS有效定位", hulc.GPS_has_valid_fix()});
    ret.append({"has_valid_position", hulc.GPS_has_valid_fix()});
    ret.append({"GPS高精度时间", hulc.GPS_high_accuracy_time()});
    ret.append({"启动以来TX队列溢出", hulc.TX_queue_overflow_since_startup()});
    ret.append({"过去一秒TX队列溢出", hulc.TX_queue_overflow_last_second()});
    ret.append({"发现过多NMEA数据", hulc.excessive_NMEA_found()});
    return ret;
}
