#include "Source_Feed_Relation.h"
#include "Config.h"
#include "Global.h"
void Source_Feed_Relation_Config::set_need_refresh() {
    for (const auto& li : Global::instance()->mode_acs.data_source_config.map.list()) {
        li->need_refresh_data_feed_key_list = true;
    }
}

void Source_Feed_Relation_Config::server(Global* g) {
    auto& svr = g->svr;
    auto& api = g->api;
    std::string name = "source_feed_relation";



    svr.Post(api + "get_" + name + "_config", [this](HTTP_Param) {
        res->setBody(warp(to_json()).to_json_string());
    });

    svr.Post(api + svr.search + name, [this, g](HTTP_Param) {
        CHECK_JSON_PARAM
        HTTP_REQUIRE_VALUE(key, params.try_get_string("key"))
        HTTP_REQUIRE_VALUE(relation, map.get(key))
        res->setBody(warp(relation->to_json()).to_json_string());
    });



    svr.Post(api + svr.update + name, [this, g](HTTP_Param) {
        CHECK_JSON_PARAM
        HTTP_REQUIRE_VALUE(key, params.try_get_string("key"))
        HTTP_REQUIRE_VALUE(ds, map.get(key))
        ds->from_json(&params);

        // 直接关闭
        g->save();
        set_need_refresh();
    });

    svr.Post(api + svr.insert + name, [g, this](HTTP_Param) {
        CHECK_JSON_PARAM
        HTTP_REQUIRE_VALUE(index, params.try_get_number<int>("index"))
        HTTP_REQUIRE_PTR(data, params.get("data"))
        HTTP_REQUIRE_VALUE(t, data->try_get_string("type"))
        std::cout << params.to_json_string() << std::endl;
        auto ds = create_source_feed_relation_from_type(t);
        ds->from_json(data);
        HTTP_REQUIRE_TRUE(map.insert(index, ds), "index")
        //std::cout << params.to_json_string() << std::endl;
        res->setBody(warp(to_json()).to_json_string());
        g->save();
        set_need_refresh();
    });

    svr.Post(api + svr.remove + name, [g, this](HTTP_Param) {
        CHECK_JSON_PARAM
        HTTP_REQUIRE_VALUE(index, params.try_get_number<int>("index"))
        HTTP_REQUIRE_TRUE(map.remove(index), "index")
        g->save();
        res->setBody(warp(to_json()).to_json_string());
        set_need_refresh();
    });
    svr.Post(api + svr.rise + name, [g, this](HTTP_Param) {
        CHECK_JSON_PARAM
        HTTP_REQUIRE_VALUE(index, params.try_get_number<int>("index"))
        HTTP_REQUIRE_TRUE(map.swap(index, index - 1), "index")
        g->save();
        res->setBody(warp(to_json()).to_json_string());
        set_need_refresh();
    });
    svr.Post(api + svr.fall + name , [g, this](HTTP_Param) {
        CHECK_JSON_PARAM
        HTTP_REQUIRE_VALUE(index, params.try_get_number<int>("index"))
        HTTP_REQUIRE_TRUE(map.swap(index, index + 1), "index")
        g->save();
        res->setBody(warp(to_json()).to_json_string());
        set_need_refresh();
    });
}
