#ifndef SOURCE_FEED_RELATION_H
#define SOURCE_FEED_RELATION_H


#include "Core/Serial/Serial.h"
#include "../global_include.h"



struct Source_Feed_Relation {
    std::string key;
    std::string type;
    std::atomic<bool> enable{};
    virtual void from_json(const Psc::JSON* that_json) {
        Get_J(key);
        Get_J(enable);
        Get_J(type);
    }

    [[nodiscard]] virtual Psc::JSON to_json() const {
        Psc::JSON ret = Psc::JSON::object();
        Ret_J(key)
        Ret_J(enable)
        Ret_J(type)
        return ret;
    }
    virtual ~Source_Feed_Relation() = default;
};

struct One_to_One_Relation : Source_Feed_Relation {
    std::string source_key;
    std::string feed_key;
    void from_json(const Psc::JSON* that_json) override {
        Source_Feed_Relation::from_json(that_json);
        Get_J(source_key)
        Get_J(feed_key)
    }
    [[nodiscard]] Psc::JSON to_json() const override {
        Psc::JSON ret = Source_Feed_Relation::to_json();
        Ret_J(source_key)
        Ret_J(feed_key)
        return ret;
    }
    ~One_to_One_Relation() override = default;
};

struct First_Source_To_All_Feed_Relation : Source_Feed_Relation {
    void from_json(const Psc::JSON* that_json) override {
        Source_Feed_Relation::from_json(that_json);
    }
    [[nodiscard]] Psc::JSON to_json() const override {
        Psc::JSON ret = Source_Feed_Relation::to_json();
        return ret;
    }
    ~First_Source_To_All_Feed_Relation() override = default;
};


inline std::shared_ptr<Source_Feed_Relation> create_source_feed_relation_from_type(const std::string& t) {
    std::shared_ptr<Source_Feed_Relation> ret{};
    if (t == "One_to_One_Relation") ret = std::make_shared<One_to_One_Relation>();
    else if (t == "First_Source_To_All_Feed_Relation") ret = std::make_shared<First_Source_To_All_Feed_Relation>();
    else {
        std::cout << "未知的  Source_Feed_Relation type 类型! t:[" << t << "]"<< std::endl;
        throw std::invalid_argument("unknown Source_Feed_Relation type: " + t);
    }
    return ret;
}

struct Source_Feed_Relation_Config {
    void from_json(const Psc::JSON* that_json) {
        auto j_list = that_json->get("list");
        for (const Psc::JSON& li : j_list->children) {
            auto p = create_source_feed_relation_from_type(li.get_string("type"));
            p->from_json(&li);
            map.push_back(p);
        }
    }
    [[nodiscard]] Psc::JSON to_json()  {
        Psc::JSON ret = Psc::JSON::object();
        Psc::JSON j_list = Psc::JSON::array();
        for (auto& p : this->map.list()) {
            j_list.append(p->to_json());
        }
        ret.append(Psc::JSON("list", j_list));
        return ret;
    }
    Ordered_Map<std::string, std::shared_ptr<Source_Feed_Relation>> map;

    static void set_need_refresh(); //通知每一个data_source 映射关系需要更新
    void server(Global* g);
};


#endif
