// Copyright 2021 Bloomberg Finance L.P
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#ifndef INCLUDED_RUMBAD_BUFFEREDPUBLISHER
#define INCLUDED_RUMBAD_BUFFEREDPUBLISHER

#include <chrono>
#include <condition_variable>
#include <string>
#include <thread>

#include <build/buildbox/local_execution.pb.h>

#include <rumbad_queue.h>
#include <rumbad_statsmanager.h>
#include <rumbad_writer.h>

#ifdef TESTING_RUMBAD_BUFFEREDPUBLISHER
#include <gtest/gtest_prod.h>
#endif

namespace rumbad {

struct SerializedMessage {
    std::chrono::time_point<std::chrono::system_clock> timestamp;
    std::string serializedData;
};

class BufferedPublisher {
  public:
    StatsManager statsManager;

    BufferedPublisher(int batchSize, std::chrono::seconds publishInterval,
                      Writer *writer);
    ~BufferedPublisher();

    void publish(const std::string &serializedMessage);

  private:
    Queue<SerializedMessage> buffer;
    int batchSize;
    bool doPublish = true;
    const int maxRetryAttempts = 10;
    std::chrono::seconds publishInterval{};
    std::thread publishThread;
    std::condition_variable waitCondition;
    std::mutex waitLock;
    Writer *writer;

    void publishBatch();
    void periodicallyPublish();

#ifdef TESTING_RUMBAD_BUFFEREDPUBLISHER
    FRIEND_TEST(BufferedPublisherTest, TestBuffering);
    FRIEND_TEST(BufferedPublisherTest, TestBatching);
    FRIEND_TEST(BufferedPublisherTest, TestBatchingCompositeWriter);
    FRIEND_TEST(BufferedPublisherTest, TestStdoutStats);
#endif
};

} // namespace rumbad

#endif
