// Copyright (c) Facebook, Inc. and its affiliates.
//
// 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.

#pragma once

#include <folly/ExceptionWrapper.h>
#include <condition_variable>
#include <mutex>
#include <vector>
#include "rsocket/Payload.h"
#include "yarpl/Refcounted.h"

namespace rsocket {
namespace tck {

class BaseSubscriber {
 public:
  virtual void request(int n) = 0;
  virtual void cancel() = 0;
  void awaitTerminalEvent();
  void awaitAtLeast(int numItems);
  void awaitNoEvents(int waitTime);
  void assertNoErrors();
  void assertError();
  void assertValues(
      const std::vector<std::pair<std::string, std::string>>& values);
  void assertValueCount(size_t valueCount);
  void assertReceivedAtLeast(size_t valueCount);
  void assertCompleted();
  void assertNotCompleted();
  void assertCanceled();

 protected:
  std::atomic<bool> canceled_{false};

  ////////////////////////////////////////////////////////////////////////////
  mutable std::mutex
      mutex_; // all variables below has to be protected with the mutex

  std::vector<std::pair<std::string, std::string>> values_;
  std::condition_variable valuesCV_;
  std::atomic<int> valuesCount_{0};

  std::vector<folly::exception_wrapper> errors_;

  std::condition_variable terminatedCV_;
  std::atomic<bool> completed_{false}; // by onComplete
  std::atomic<bool> errored_{false}; // by onError
  ////////////////////////////////////////////////////////////////////////////
};

} // namespace tck
} // namespace rsocket
