#include "sla_description.h"

#include <saas/deploy_manager/protos/sla_description.pb.h>
#include <library/cpp/protobuf/util/pb_io.h>

#define DESCRIPTION_FILE_CONTENT_GENERATOR_TYPE "sla_description_yconf"

namespace NRTYDeploy {

    TString TSlaDescriptionFileContentGenerator::GetType() const {
        return DESCRIPTION_FILE_CONTENT_GENERATOR_TYPE;
    }

    void TSlaDescriptionFileContentGenerator::DoDeserialize(const NJson::TJsonValue& json) {
        TFileContentGenerator::DoDeserialize(json);
        Path = json["path"].GetStringRobust();
        Path.Fix();
        Service = json["service"].GetStringRobust();
        Version = json["version"].GetIntegerRobust();
    }

    void TSlaDescriptionFileContentGenerator::Serialize(NJson::TJsonValue& json) const {
        json.InsertValue("type", GetType());
        json.InsertValue("service", Service);
        json.InsertValue("path", Path.GetPath());
        json.InsertValue("version", Version);
    }

    TString TSlaDescriptionFileContentGenerator::GetRename(const TContext& context) const {
        return GetRename(Service ? Service : context.SlotInfo.Service);
    }

    bool TSlaDescriptionFileContentGenerator::GetContent(TString& result, const ICommonData& common, const TContext& context) const {
        TStringStream out;
        out << "<Sla>\n";
        ProduceContent(out, common, context);
        out << "</Sla>\n";

        result = out.Str();
        return true;
    }

    void TSlaDescriptionFileContentGenerator::ProduceContent(IOutputStream& out, const ICommonData& common, const TContext&) const {
        if (!Path) {
            // FIXME
            return;
        }

        const auto srcPath = GetSrcFilePath(Path);
        TString confText;
        if (!common.GetStorage().GetValue(srcPath.GetPath(), confText, Version)) {
            return;
        }

        NSaasProto::TSlaDescription proto;
        TStringInput in(confText);
        if (!TryParseFromTextFormat(in, proto, EParseFromTextFormatOption::AllowUnknownField)) {
            ERROR_LOG << "Failed to parse sla_description proto" << Endl;
            return;
        }

        for (const auto& ctypeSla : proto.GetCTypeSLA()) {
            const auto& ctype = ctypeSla.GetCtype();
            const auto& abcId = ctypeSla.GetABCUserService();
            if (!ctype || !abcId) {
                continue;
            }
            out << "    <Ctype>\n";
            out << "        Ctype: " << ctype << "\n";
            out << "        AbcUserService: " << abcId << "\n";
            out << "    </Ctype>\n";
        }
    }

    TSlaDescriptionFileContentGenerator::TFactory::TRegistrator<TSlaDescriptionFileContentGenerator> TSlaDescriptionFileContentGenerator::Registrar(DESCRIPTION_FILE_CONTENT_GENERATOR_TYPE);

}
