//
// Created by jonathan.hanks on 1/27/21.
//

#ifndef DAQD_TRUNK_PUB_PLUGIN_ZLIB_HH
#define DAQD_TRUNK_PUB_PLUGIN_ZLIB_HH

#include <cds-pubsub/pub.hh>
#include "pub_intl.hh"
#include "zstd_common.hh"

namespace pub_sub
{

    namespace detail
    {
        class ZStdPublisherInstance : public pub_sub::plugins::PublisherInstance
        {
        public:
            ZStdPublisherInstance(
                int                                       compression_level,
                pub_sub::PubDebugNotices&                 debug,
                pub_sub::plugins::UniquePublisherInstance next_stage )
                : deflate_( compression_level ), next_stage_{ std::move(
                                                     next_stage ) }
            {
            }
            ~ZStdPublisherInstance( ) override = default;

            void
            publish( pub_sub::KeyType key, pub_sub::Message msg ) override
            {
                try
                {
                    msg = deflate_( msg );
                }
                catch ( std::runtime_error& )
                {
                    // deflate_ may throw std::runtime_error, on a zlib error
                    // ignore it (drop the message)
                }
                next_stage_->publish( key, msg );
            }

        private:
            DeflateStream                             deflate_;
            pub_sub::plugins::UniquePublisherInstance next_stage_;
        };
    } // namespace detail
} // namespace pub_sub

#endif // DAQD_TRUNK_PUB_PLUGIN_ZLIB_HH
