#include "plain.h"
#include <util/string/subst.h>

#define PLAIN_FILE_CONTENT_GENERATOR_TYPE "plain"

namespace NRTYDeploy {

    TPlainFileContentGenerator::TPlainFileContentGenerator()
    {}

    TPlainFileContentGenerator::TPlainFileContentGenerator(const TFsPath& path, const ICommonData& data, i64 version)
        : Path(path)
        , Version(version)
    {
        Path.Fix();
        if (Version == -1 && !data.GetStorage().GetVersion(Path.GetPath(), Version))
            ythrow yexception() << "cannot get version for " << Path.GetPath();
    }

    TString TPlainFileContentGenerator::GetType() const {
        return PLAIN_FILE_CONTENT_GENERATOR_TYPE;
    }

    void TPlainFileContentGenerator::Serialize(NJson::TJsonValue& json) const {
        TFileContentGenerator::Serialize(json);
        json.InsertValue("path", Path.GetPath());
        json.InsertValue("version", Version);
    }

    TString TPlainFileContentGenerator::GetRename(const TContext& context) const {
        TString name = Path.GetName();
        name = name.substr(0, name.find('$'));
        SubstGlobal(name, ServiceNameMacros.data(), context.SlotInfo.Service);
        return name;
    }

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

    bool TPlainFileContentGenerator::DoGetContent(TString& result, const ICommonData& common, const TContext& context) const {
        if (common.GetStorage().GetValue(Path.GetPath(), result, Version)) {
            SubstGlobal(result, ServiceNameMacros.data(), context.SlotInfo.Service);
            return true;
        }
        return false;
    }

    void TPlainFileContentGenerator::SetLastVersion() {
        Version = -1;
    }

    TString TPlainFileContentGenerator::GetCacheKey(const TContext& /*context*/) const {
        return "const";
    }

    TPlainFileContentGenerator::TFactory::TRegistrator<TPlainFileContentGenerator> TPlainFileContentGenerator::Registrar(PLAIN_FILE_CONTENT_GENERATOR_TYPE);
}
