#include "cached.h"

namespace NRTYDeploy {

    bool TCachedFileContentGenerator::GetContent(TString& result, const ICommonData& common, const TContext& context) const {
        if (const auto record = TCache::Get<TCallbacks>(common, *this, context)) {
            result = record->Content;
            return true;
        }
        return false;
    }

    bool TCachedFileContentGenerator::GetContentHash(TString& result, const ICommonData& common, const TContext& context) const {
        if (const auto record = TCache::Get<TCallbacks>(common, *this, context)) {
            result = record->Hash;
            return true;
        }
        return false;
    }

    void TCachedFileContentGenerator::ClearCaches() {
        TCache::Clear<TCallbacks>();
    }

    TCachedFileContentGenerator::TCacheRecord* TCachedFileContentGenerator::TCallbacks::CreateObject(const ICommonData& common, const TCachedFileContentGenerator& generator, const TContext& context) const {
        THolder<TCacheRecord> result = MakeHolder<TCacheRecord>();
        if (!generator.DoGetContent(result->Content, common, context))
            return nullptr;
        result->Hash = MD5::Calc(result->Content);
        return result.Release();
    }

    TCachedFileContentGenerator::TCallbacks::TKey TCachedFileContentGenerator::TCallbacks::GetKey(const ICommonData& common, const TCachedFileContentGenerator& generator, const TContext& context) const {
        NJson::TJsonValue json;
        generator.Serialize(json);
        TString generatroStr = json.GetStringRobust();
        TString contextStr = generator.GetCacheKey(context);
        TString storageStr = common.GetConfig().GetStorageOptions().SerializeToJson().GetStringRobust();
        MD5 calc;
        calc.Update(generatroStr.data(), generatroStr.size());
        calc.Update(contextStr.data(), contextStr.size());
        calc.Update(storageStr.data(), storageStr.size());
        char buf[33];
        return calc.End(buf);
    }
}
