#include "scripts_helper.h"
#include <saas/deploy_manager/scripts/common/deploy/deploy_builder.h>
#include <library/cpp/json/json_reader.h>
#include <library/cpp/json/json_writer.h>

namespace NRTYDeploy {

    TString TNodesStructure::Serialize() const {
        NJson::TJsonValue json(NJson::JSON_MAP);
        json.InsertValue("serializing_version", SerializingVersion);
        json.InsertValue("timestamp", Timestamp.GetValue());
        NJson::TJsonValue& files = json.InsertValue("files", NJson::JSON_ARRAY);
        for (const_iterator i = begin(); i != end(); ++i)
            (*i)->Serialize(files.AppendValue(NJson::JSON_MAP));
        return NJson::WriteJson(&json, true, true, false);;
    }

    NJson::TJsonValue TNodesStructure::SerializeWithContext(const TFileContentGenerator::TContext& context) const {
        NJson::TJsonValue result(NJson::JSON_ARRAY);
        for (const_iterator i = begin(); i != end(); ++i) {
            TString rename = (*i)->GetRename(context);
            if (!rename)
                continue;
            TString url;
            if (!(*i)->SerializeWithContext(url, context))
                continue;
            NJson::TJsonValue& node = result.AppendValue(NJson::JSON_MAP);
            node.InsertValue("name", "not used now");
            node.InsertValue("url", url);
            node.InsertValue("rename", rename);
            node.InsertValue("version", -1);
        }
        return result;
    }

    bool TNodesStructure::Deserialize(const TString& json, i64* version) {
        TStringInput si(json);
        NJson::TJsonValue value;
        if (!ReadJsonTree(&si, &value))
            return false;
        if (!value.IsMap() || !value.Has("serializing_version") || value["serializing_version"].GetUInteger() != SerializingVersion) {
            if (version)
                *version = -1;
            return false;
        }

        if (value.Has("timestamp"))
            Timestamp = TInstant::MicroSeconds(value["timestamp"].GetUIntegerRobust());

        const NJson::TJsonValue& files = value["files"];
        for (NJson::TJsonValue::TArray::const_iterator i = files.GetArray().begin(); i != files.GetArray().end(); ++i) {
            TFileContentGenerator::TPtr node(TFileContentGenerator::Deserialize(*i));
            if (!!node)
                push_back(node);
        }
        return true;
    }
}
