#pragma once
#include <memory_resource>
#include <string_view>
#include "Data_Source_Handler.h"
namespace Psc {
class SM_RingBuffer;
}
class Data_Source;
std::shared_ptr<Data_Source> create_from_json(const Psc::JSON* that_json);
class Input_Format {
public:
    Input_Format() {
        test_v.resize(static_cast<size_t>(SSR::Downlink_Format::Unknown));
    }
    Psc::JSON to_json() {
        std::lock_guard g(mtx);
        Psc::JSON ret = Psc::JSON::object();
        for (auto e : magic_enum::enum_values<SSR::Downlink_Format>()) {
            std::string_view value_view = magic_enum::enum_name(e);
            std::string value(value_view.begin(), value_view.end());
            if (value == Psc::to_string(SSR::Downlink_Format::Unknown))
                continue;
            auto ev = static_cast<std::uint8_t>(e);
            bool it = test_v[ev];
            ret.append({value, it});
        }
        return ret;
    }
    void from_json(const Psc::JSON* json) {
        std::lock_guard g(mtx);
        for (auto e : magic_enum::enum_values<SSR::Downlink_Format>()) {
            std::string_view value_view = magic_enum::enum_name(e);
            std::string value(value_view.begin(), value_view.end());
            if (value == Psc::to_string(SSR::Downlink_Format::Unknown))
                continue;
            auto use = json->get_bool(value);
            auto ev = static_cast<std::uint8_t>(e);
            test_v[ev] = use;
        }
    }
    bool test(SSR::Downlink_Format df) {
        std::lock_guard g(mtx);
        auto dfv = static_cast<std::uint8_t>(df);
        if (dfv >= static_cast<std::uint8_t>(SSR::Downlink_Format::Unknown))
            return false;
        return test_v[dfv];
    }
    bool test(std::uint8_t dfv) {
        std::lock_guard g(mtx);
        if (dfv >= static_cast<std::uint8_t>(SSR::Downlink_Format::Unknown))
            return false;
        return test_v[dfv];
    }
protected:
    std::mutex mtx;
    std::vector<bool> test_v;
};
class Data_Source_Map_Display_Data {
public:
    bool base_station_show = true;
    bool aircraft_show = true;
    bool constant_screen_size = true;
    std::string color = "#1677ff";
    std::string track_point_color = "#ffff00";
    std::string base_station_color = "#1677ff";
    std::uint32_t aircraft_pixel_size = 50;
    std::uint32_t base_station_pixel_size = 100;
    std::uint32_t track_point_pixel_size = 8;
    double aircraft_scale = 1.0;
    double base_station_scale = 1.0;
    bool show_icao = true;
    bool show_call_sign = false;
    bool show_fly_status = false;
    bool show_heading = false;
    PSC_USE_JSON
};
class Data_Source_Map_Display_Config {
public:
    Data_Source_Map_Display_Data map2d;
    Data_Source_Map_Display_Data map3d;
    [[nodiscard]] Psc::JSON to_base_json() const {
        auto ret = Psc::JSON::object();
        ret.append({"map2d", map2d.to_base_json()});
        ret.append({"map3d", map3d.to_base_json()});
        return ret;
    }
    void from_base_json(const Psc::JSON* that_json) {
        if (that_json == nullptr || that_json->valueType != Psc::Object)
            throw Psc::json_assign_error(std::make_error_code(std::errc::invalid_argument), "map_display");
        map2d.from_base_json(that_json->get("map2d"));
        map3d.from_base_json(that_json->get("map3d"));
    }
};
class Data_Source_Data {
public:
    bool base_station_has_valid_position{};
    Data_Source_Map_Display_Config map_display;
    double lat{};
    double lon{};
    double alt{};
    bool ignore_msg_time = false;
    bool update_form_gps{};
    bool keep_mode = true;
    [[nodiscard]] Psc::JSON to_base_json() const {
        auto ret = Psc::JSON::object();
        Ret_J(base_station_has_valid_position) ret.append({"map_display", map_display.to_base_json()});
        Ret_J(lat) Ret_J(lon) Ret_J(alt) Ret_J(ignore_msg_time) Ret_J(update_form_gps) Ret_J(keep_mode) return ret;
    }
    void from_base_json(const Psc::JSON* that_json) {
        Get_J(base_station_has_valid_position)
        map_display.from_base_json(that_json->get("map_display"));
        Get_J(lat) Get_J(lon) Get_J(alt) Get_J(ignore_msg_time) Get_J(update_form_gps) Get_J(keep_mode)
    }
};
namespace adminive {
template <>
struct Type_Descriptor<Data_Source_Map_Display_Data> {
    static auto get() {
        using T = Data_Source_Map_Display_Data;
        return object<T>("data_source_map_display", "地图显示",
                         ADMINIVE_FIELD_LABEL(T, base_station_show, "显示基站").creatable().editable().boolean_input(),
                         ADMINIVE_FIELD_LABEL(T, aircraft_show, "显示飞机").creatable().editable().boolean_input(),
                         ADMINIVE_FIELD_LABEL(T, constant_screen_size, "固定屏幕尺寸").creatable().editable().boolean_input(),
                         ADMINIVE_FIELD_LABEL(T, color, "飞机标注颜色").creatable().editable().color_input(),
                         ADMINIVE_FIELD_LABEL(T, track_point_color, "航迹点颜色").creatable().editable().color_input(),
                         ADMINIVE_FIELD_LABEL(T, base_station_color, "基站颜色").creatable().editable().color_input(),
                         ADMINIVE_FIELD_LABEL(T, aircraft_pixel_size, "飞机显示大小").creatable().editable().number_input(),
                         ADMINIVE_FIELD_LABEL(T, base_station_pixel_size, "基站显示大小").creatable().editable().number_input(),
                         ADMINIVE_FIELD_LABEL(T, track_point_pixel_size, "轨迹点大小").creatable().editable().number_input(),
                         ADMINIVE_FIELD_LABEL(T, aircraft_scale, "飞机缩放比例").creatable().editable().number_input(),
                         ADMINIVE_FIELD_LABEL(T, base_station_scale, "基站显示大小").creatable().editable().number_input(),
                         ADMINIVE_FIELD_LABEL(T, show_icao, "显示 ICAO").creatable().editable().boolean_input(),
                         ADMINIVE_FIELD_LABEL(T, show_call_sign, "显示呼号").creatable().editable().boolean_input(),
                         ADMINIVE_FIELD_LABEL(T, show_fly_status, "显示飞行状态").creatable().editable().boolean_input(),
                         ADMINIVE_FIELD_LABEL(T, show_heading, "显示飞机角度").creatable().editable().boolean_input());
    }
};
template <>
struct Type_Descriptor<Data_Source_Map_Display_Config> {
    static auto get() {
        using T = Data_Source_Map_Display_Config;
        return object<T>("data_source_map_display_config", "地图显示配置",
                         ADMINIVE_FIELD_LABEL(T, map2d, "2D 地图").creatable().editable(),
                         ADMINIVE_FIELD_LABEL(T, map3d, "3D 地图").creatable().editable());
    }
};
template <>
struct Type_Descriptor<Data_Source_Data> {
    static auto get() {
        using T = Data_Source_Data;
        return object<T>("data_source_config", "数据源公共配置",
                         ADMINIVE_FIELD_LABEL(T, base_station_has_valid_position, "基站有效定位").creatable().editable().boolean_input(),
                         ADMINIVE_FIELD_LABEL(T, map_display, "地图显示").creatable().editable(),
                         ADMINIVE_FIELD_LABEL(T, lat, "纬度").creatable().editable().number_input(),
                         ADMINIVE_FIELD_LABEL(T, lon, "经度").creatable().editable().number_input(),
                         ADMINIVE_FIELD_LABEL(T, alt, "高度").creatable().editable().number_input(),
                         ADMINIVE_FIELD_LABEL(T, ignore_msg_time, "忽略消息时间戳").creatable().editable().boolean_input(),
                         ADMINIVE_FIELD_LABEL(T, update_form_gps, "从 GPS 更新位置").creatable().editable().boolean_input(),
                         ADMINIVE_FIELD_LABEL(T, keep_mode, "基站最大范围保持模式").creatable().editable().boolean_input());
    }
};
}
class Data_Source : public std::enable_shared_from_this<Data_Source>, public Data_Source_Handler {
public:
    adminive::Managed_Value<Data_Source_Data> settings;
    std::shared_ptr<Data_Source> that();
    virtual asio::awaitable<std::string> read_coro() {
        co_return "";
    }
    bool registered() const;
    virtual Psc::JSON get_custom_state_json() = 0;
    Psc::JSON get_state();
    std::string last_char;
    Data_Source();
    asio::awaitable<void> loop_coro() final;
    std::shared_ptr<SSR::Mode_Msg> last_prase_msg = nullptr;
    virtual asio::awaitable<void> handle_in_loop_coro() {
        co_return;
    }
    virtual bool discard_input_packet(std::string_view) {
        return false;
    }
    Frequency_Limit statistic_fl;
    Psc::JSON statistic_json() {
        Psc::JSON ret = With_Loop_Coro::to_base_json();
        ret.append({"aircraft_total", get_aircraft_num()});
        ret.append({"aircraft_with_position", have_pos_aircraft_num});
        ret.append({"mode_ac_statistic", mode_ac_statistic.to_json()});
        ret.append({"mode_s_statistic", mode_s_statistic.to_json()});
        ret.append({"all_connect_feed", get_all_connect_feed_status()});
        return ret;
    }
    virtual Psc::JSON to_json() {
        return With_Loop_Coro::to_base_json() += settings.read([](const auto& value) { return value.to_base_json(); });
    }
    virtual void from_json(const Psc::JSON* that_json) {
        With_Loop_Coro::from_base_json(that_json);
        settings.write([&](auto& value) {
            value.from_base_json(that_json);
        });
    }
    std::string buffer;
    std::atomic_bool ask_sleep = false;
};
class TCP_Client_Data_Source_Data {
public:
    std::string ip;
    std::uint16_t port{};
    PSC_USE_JSON
};
namespace adminive {
template <>
struct Type_Descriptor<TCP_Client_Data_Source_Data> {
    static auto get() {
        using T = TCP_Client_Data_Source_Data;
        return object<T>("tcp_client_data_source", "TCP 客户端配置",
                         ADMINIVE_FIELD_LABEL(T, ip, "IP 地址").creatable().editable().text_input(),
                         ADMINIVE_FIELD_LABEL(T, port, "端口").creatable().editable().number_input());
    }
};
}
class TCP_Client_Data_Source : public Data_Source {
public:
    adminive::Managed_Value<TCP_Client_Data_Source_Data> specific;
    asio::awaitable<void> handle_in_loop_coro() override {
        co_await cli.tick_coro();
        co_return;
    }
    Psc::JSON get_custom_state_json() override {
        Psc::JSON ret = Psc::JSON::object();
        ret.append({"transport_state", Psc::to_string(cli.state.load())});
        ret.append({"transport", cli.statistics.to_json()});
        return ret;
    }
    Psc::asio_socket::TCP_Client_Coro cli;
    ~TCP_Client_Data_Source() override = default;
    TCP_Client_Data_Source() {
        type = "TCP_Client_Data_Source";
    }
    asio::awaitable<void> _open() override {
        const auto value = specific.read([](const auto& value) { return value; });
        Psc::asio_socket::Sockaddr_In addr;
        addr.ip = value.ip;
        addr.port = value.port;
        cli.set_dest_address(addr);
        cli.create();
        co_await cli.connect_coro();
        co_return;
    }
    asio::awaitable<void> _close() override {
        co_await cli.close_coro();
        co_return;
    }
    Psc::JSON to_json() override {
        return Data_Source::to_json() += specific.read([](const auto& value) { return value.to_base_json(); });
    }
    void from_json(const Psc::JSON* that_json) override {
        Data_Source::from_json(that_json);
        specific.write([&](auto& value) {
            value.from_base_json(that_json);
        });
    }
    asio::awaitable<std::string> read_coro() override {
        co_return co_await cli.read_coro();
    }
};
class Serial_Data_Source_Data {
public:
    std::string port_name;
    Baud_Rate_Type baud_rate{};
    PSC_USE_JSON
};
namespace adminive {
template <>
struct Type_Descriptor<Serial_Data_Source_Data> {
    static auto get() {
        using T = Serial_Data_Source_Data;
        return object<T>("serial_data_source", "串口数据源配置",
                         ADMINIVE_FIELD_LABEL(T, port_name, "串口名称").creatable().editable().text_input(),
                         ADMINIVE_FIELD_LABEL(T, baud_rate, "波特率").creatable().editable().select_input());
    }
};
}
class Serial_Data_Source : public Data_Source {
public:
    adminive::Managed_Value<Serial_Data_Source_Data> specific;
    Psc::JSON get_custom_state_json() override {
        Psc::JSON ret = Psc::JSON::object();
        ret.append({"serial_open", serial_open.load()});
        if (serial)
            ret.append({"transport", serial->statistics.to_json()});
        return ret;
    }
    Serial_Data_Source() {
        type = "Serial_Data_Source";
    }
    asio::awaitable<void> _open() override {
        const auto value = specific.read([](const auto& value) { return value; });
        serial = std::make_unique<Psc::serial::Serial_Coro>();
        serial->set_serial_name(value.port_name);
        serial->set_baud_rate(value.baud_rate);
        serial->set_parity(Psc::serial::Parity::NoParity);
        serial->set_data_bits(Psc::serial::DataBits::Data8);
        serial->set_stop_bits(Psc::serial::StopBits::OneStop);
        serial->set_flow_control(Psc::serial::FlowControl::HardwareControl);
        serial->set_buffer_byte_size(10 * 1024);
        serial_open = serial->open();
        if (!serial_open)
            std::cerr << "createSerial " + value.port_name + ":" + std::to_string(value.baud_rate) + " 打开串口失败！\n";
        co_return;
    }
    asio::awaitable<void> _close() override {
        if (serial)
            serial->close();
        serial_open = false;
        co_return;
    }
    asio::awaitable<void> handle_in_loop_coro() override {
        if (serial)
            co_await serial->tick_coro();
        co_return;
    }
    asio::awaitable<std::string> read_coro() override {
        if (!serial)
            co_return "";
        co_return co_await serial->read_coro();
    }
    Psc::JSON to_json() override {
        return Data_Source::to_json() += specific.read([](const auto& value) { return value.to_base_json(); });
    }
    void from_json(const Psc::JSON* that_json) override {
        Data_Source::from_json(that_json);
        specific.write([&](auto& value) {
            value.from_base_json(that_json);
        });
    }
    std::unique_ptr<Psc::serial::Serial_Coro> serial{};
    std::atomic_bool serial_open{};
    ~Serial_Data_Source() override {
        if (serial)
            serial->close();
    }
};
enum class File_Data_Type {
    SIMPLE_BIN_Blank, // 没有1a转义�?
    BIN_Blank_Text,
    AVR,
    BIN_Text,
    BIN_Blank_One_Line_With_Escape,
    BIN_Blank_One_Line_No_Escape,
    BIN,
    Unknown
    // 纯粹的二进制
};
enum Play_Mode { one, loop, analysis, time_batch };
class File_Data_Source_Data {
public:
    std::string file_path;
    File_Data_Type data_type = File_Data_Type::BIN_Blank_Text;
    Play_Mode play_mode = Play_Mode::one;
    PSC_USE_JSON
};
namespace adminive {
template <>
struct Type_Descriptor<File_Data_Source_Data> {
    static auto get() {
        using T = File_Data_Source_Data;
        return object<T>("file_data_source", "文件数据源配置",
                         ADMINIVE_FIELD_LABEL(T, file_path, "文件路径").creatable().editable().text_input(),
                         ADMINIVE_FIELD_LABEL(T, data_type, "数据格式").creatable().editable().select_input(),
                         ADMINIVE_FIELD_LABEL(T, play_mode, "播放模式").creatable().editable().select_input());
    }
};
}
class File_Data_Source : public Data_Source {
public:
    adminive::Managed_Value<File_Data_Source_Data> specific;
    bool have_report_play_back_all_success = false;
    std::string state = "null";
    Psc::JSON get_custom_state_json() override {
        std::lock_guard lock(mtx);
        const auto total_records = part_infos.size();
        const auto current_index = static_cast<std::size_t>(std::max<long long>(index, 0));
        Psc::JSON playback = Psc::JSON::object();
        playback.append({"state", state});
        playback.append({"virtual_time", player_clock.get_cur_time_point().to_string()});
        playback.append({"speed_rate", player_clock.playback_speed_rate});
        playback.append({"current_index", current_index});
        playback.append({"total_records", total_records});
        playback.append({"remaining_records", total_records > current_index ? total_records - current_index : 0});
        playback.append({"progress_percent", total_records == 0 ? 0.0 : static_cast<double>(current_index) * 100.0 / static_cast<double>(total_records)});
        playback.append({"loop_total", loop_total.load()});
        playback.append({"raw_read", raw_read_statistics.to_json()});
        playback.append({"conversion_dropped", conversion_dropped_statistics.to_json()});
        Psc::JSON ret = Psc::JSON::object();
        ret.append({"playback", playback});
        return ret;
    }
    File_Data_Source() {
        type = "File_Data_Source";
    }
    ~File_Data_Source() override = default;
    void before_handle_msg(std::shared_ptr<SSR::Mode_Msg>& msg) override;
    struct Cache_Msg {
        explicit Cache_Msg(std::shared_ptr<SSR::Mode_S_Msg> msg) : msg(std::move(msg)) {
        }
        SSR::Play_Back_Time_Point time() const {
            return SSR::Play_Back_Time_Point{day_num, msg->mlat_timestamp.daysec};
        }
        std::uint64_t day_num = 0;
        std::shared_ptr<SSR::Mode_S_Msg> msg;
    };
    Player_Clock player_clock;
    Psc::Throughput_Statistics raw_read_statistics;
    Psc::Throughput_Statistics conversion_dropped_statistics;
    std::atomic<std::uint64_t> loop_total{};
    std::shared_ptr<Cache_Msg> pre_cache = nullptr;
    std::deque<std::shared_ptr<Cache_Msg>> cache_list;
    std::string get_true_file_path() const {
        return Psc::get_abs_path(specific.member<&File_Data_Source_Data::file_path>().read([](const auto& value) { return value; }));
    }
    asio::awaitable<void> _close() override;
    asio::awaitable<void> _open() override;
    std::vector<std::string> readBinaryFileAsString(std::string_view filepath, size_t part_size);
    void from_json(const Psc::JSON* that_json) override {
        Data_Source::from_json(that_json);
        specific.write([&](auto& value) {
            value.from_base_json(that_json);
        });
    }
    Psc::JSON to_json() override {
        return Data_Source::to_json() += specific.read([](const auto& value) { return value.to_base_json(); });
    }
    void origin_data_transform_mode_data(std::string& data) override;
    void handle_mode_s(std::shared_ptr<SSR::Mode_S_Msg>& msg) override;
protected:
    std::optional<std::string> get_raw_line(int& ret_index);
    long long index = 0;
    std::vector<std::string> part_infos;
    std::mutex mtx;
};
class Dll_Data_Source_Data {
public:
    std::string library_path;
    std::string function_name;
    File_Data_Type data_type = File_Data_Type::BIN_Blank_Text;
    std::size_t buffer_size{};
    PSC_USE_JSON
};
namespace adminive {
template <>
struct Type_Descriptor<Dll_Data_Source_Data> {
    static auto get() {
        using T = Dll_Data_Source_Data;
        return object<T>("dll_data_source", "DLL 数据源配置",
                         ADMINIVE_FIELD_LABEL(T, library_path, "库路径").creatable().editable().text_input(),
                         ADMINIVE_FIELD_LABEL(T, function_name, "函数名").creatable().editable().text_input(),
                         ADMINIVE_FIELD_LABEL(T, data_type, "数据格式").creatable().editable().select_input(),
                         ADMINIVE_FIELD_LABEL(T, buffer_size, "读取缓冲区大小").creatable().editable().number_input());
    }
};
}
class Dll_Data_Source : public Data_Source {
public:
    adminive::Managed_Value<Dll_Data_Source_Data> specific;
    Psc::JSON get_custom_state_json() override;
    Psc::JSON backlog_state_json() const;
    Psc::Throughput_Statistics read_statistics;
    Dll_Data_Source() {
        type = "Dll_Data_Source";
    }
    ~Dll_Data_Source() override = default;
    std::pmr::vector<std::uint8_t> buffer;
    void from_json(const Psc::JSON* that_json) override {
        Data_Source::from_json(that_json);
        const auto buffer_size = specific.write([&](auto& value) {
            value.from_base_json(that_json);
            return value.buffer_size;
        });
        buffer.resize(buffer_size);
    }
    Psc::JSON to_json() override {
        return Data_Source::to_json() += specific.read([](const auto& value) { return value.to_base_json(); });
    }
    void* lib{};
    using Func_Type = size_t (*)(char* buf, std::size_t max_len);
    Func_Type read_func_ptr{};
    using Call_Back = void (*)(char* buf, std::size_t len);
    using set_Call_back = void (*)(Call_Back);
    std::string state;
    mutable std::mutex state_mtx;
    asio::awaitable<void> _close() override {
        Psc::free_library(lib);
        co_return;
    }
    asio::awaitable<void> _open() override {
        const auto value = specific.read([](const auto& value) { return value; });
        {
            auto r = Psc::try_load_library(Psc::get_abs_path(value.library_path));
            if (!r) {
                std::lock_guard lock(state_mtx);
                state = Psc::platform_2_utf8(r.error().message());
                co_return;
            }
            lib = r.value();
        }
        {
            auto r = Psc::try_load_function(lib, value.function_name);
            if (!r) {
                std::lock_guard lock(state_mtx);
                state = Psc::platform_2_utf8(r.error().message());
                std::cout << LOG_POS << "  [" << value.function_name << "]  函数指针加载失败!" << std::endl;
                co_return;
            }
            read_func_ptr = (Func_Type)r.value();
        }
        {
            std::lock_guard lock(state_mtx);
            state = "加载成功";
        }
        co_return;
    }
    bool discard_input_packet(std::string_view packet) override;
    void origin_data_transform_mode_data(std::string& data) override;
private:
    static constexpr std::size_t backlog_read_size = 8 * 1024 * 1024;
    bool drop_mode_ac_for_batch_{};
    std::atomic_bool backlog_active_{};
    std::atomic<std::uint64_t> backlog_events_total_{};
    std::atomic<std::uint64_t> backlog_batches_total_{};
    std::atomic<std::uint64_t> backlog_raw_bytes_total_{};
    std::atomic<std::uint64_t> dropped_mode_ac_frames_total_{};
    std::atomic<std::uint64_t> dropped_mode_ac_bytes_total_{};
    std::atomic<std::size_t> last_batch_raw_bytes_{};
    std::atomic<std::size_t> largest_batch_raw_bytes_{};
    std::atomic<std::size_t> last_read_request_bytes_{};
};
class Shared_Memory_Data_Source_Data {
public:
    std::string shared_memory_name;
    std::uint64_t shared_memory_size{};
    File_Data_Type data_type = File_Data_Type::BIN_Blank_Text;
    PSC_USE_JSON
};
namespace adminive {
template <>
struct Type_Descriptor<Shared_Memory_Data_Source_Data> {
    static auto get() {
        using T = Shared_Memory_Data_Source_Data;
        return object<T>("shared_memory_data_source", "共享内存数据源配置",
                         ADMINIVE_FIELD_LABEL(T, shared_memory_name, "共享内存名称").creatable().editable().text_input(),
                         ADMINIVE_FIELD_LABEL(T, shared_memory_size, "共享内存大小").creatable().editable().number_input(),
                         ADMINIVE_FIELD_LABEL(T, data_type, "数据格式").creatable().editable().select_input());
    }
};
}
class Shared_Memory_Data_Source : public Data_Source {
public:
    adminive::Managed_Value<Shared_Memory_Data_Source_Data> specific;
    Psc::JSON get_custom_state_json() override {
        Psc::JSON ret = Psc::JSON::object();
        ret.append({"shared_memory_open", shared_memory_open.load()});
        return ret;
    }
    void from_json(const Psc::JSON* that_json) override {
        Data_Source::from_json(that_json);
        specific.write([&](auto& value) {
            value.from_base_json(that_json);
        });
    }
    Psc::JSON to_json() override {
        return Data_Source::to_json() += specific.read([](const auto& value) { return value.to_base_json(); });
    }
    asio::awaitable<void> _open() override;
    asio::awaitable<void> _close() override;
    void origin_data_transform_mode_data(std::string& data) override;
protected:
    std::unique_ptr<Psc::SM_RingBuffer> sm;
    std::atomic_bool shared_memory_open{};
};
inline std::shared_ptr<Data_Source> create_data_source_from_type(std::string_view t) {
    std::shared_ptr<Data_Source> ret{};
    if (t == "Serial_Data_Source")
        ret = std::make_shared<Serial_Data_Source>();
    else if (t == "TCP_Client_Data_Source")
        ret = std::make_shared<TCP_Client_Data_Source>();
    else if (t == "File_Data_Source")
        ret = std::make_shared<File_Data_Source>();
    else if (t == "Dll_Data_Source")
        ret = std::make_shared<Dll_Data_Source>();
    else if (t == "Shared_Memory_Data_Source")
        ret = std::make_shared<Shared_Memory_Data_Source>();
    else {
        std::cout << "未知 Data_Source type类型!" << std::endl;
        throw std::invalid_argument("unknown Data_Source type: " + std::string(t));
    }
    ret->type = std::string(t);
    return ret;
}
struct Data_Source_Config {
    Ordered_Map<std::string, std::shared_ptr<Data_Source>> map;
    Data_Source_Config() = default;
    void init(const Psc::JSON* that_json) {
        if (that_json == nullptr || that_json->valueType != Psc::Object)
            throw Psc::json_assign_error(std::make_error_code(std::errc::invalid_argument), "data_source");
        auto list = that_json->get("list");
        if (list == nullptr || list->valueType != Psc::Array)
            throw Psc::json_assign_error(std::make_error_code(std::errc::invalid_argument), "data_source.list");
        for (auto& it : list->children) {
            auto ds = create_from_json(&it);
            map.push_back(ds);
        }
    }
    Psc::JSON list() const {
        auto connect_json = Psc::JSON::array();
        for (auto& it : map.list()) {
            connect_json.children.emplace_back(it->to_json());
        }
        return connect_json;
    }
    Psc::JSON to_json() const {
        Psc::JSON ret = Psc::JSON::object();
        ret.append({"list", list()});
        return ret;
    }
    void server(Global* g);
};
