// Copyright 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include <memory>

#include "base/memory/ptr_util.h"
#include "blimp/common/blob_cache/id_util.h"
#include "blimp/common/blob_cache/test_util.h"
#include "blimp/net/blob_channel/helium_blob_receiver_delegate.h"
#include "blimp/net/blob_channel/helium_blob_sender_delegate.h"
#include "blimp/net/blob_channel/mock_blob_channel_receiver.h"
#include "blimp/net/test_common.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"

namespace blimp {
namespace {

using testing::_;
using testing::SaveArg;

const char kBlobId[] = "foo1";
const char kBlobPayload[] = "bar1";

class HeliumBlobChannelTest : public testing::Test {
 public:
  HeliumBlobChannelTest() : receiver_delegate_(new HeliumBlobReceiverDelegate) {
    receiver_delegate_->SetReceiver(&mock_receiver_);
    sender_delegate_.set_outgoing_message_processor(
        base::WrapUnique(receiver_delegate_));
  }

  ~HeliumBlobChannelTest() override {}

 protected:
  const std::string blob_id_ = CalculateBlobId(kBlobId);

  MockBlobChannelReceiver mock_receiver_;
  HeliumBlobReceiverDelegate* receiver_delegate_;
  HeliumBlobSenderDelegate sender_delegate_;

 private:
  DISALLOW_COPY_AND_ASSIGN(HeliumBlobChannelTest);
};

// Verifies the content of BlimpMessages generated by the Sender.
TEST_F(HeliumBlobChannelTest, TransferBlobContents) {
  BlimpMessage captured_msg;
  MockBlimpMessageProcessor* mock_processor = new MockBlimpMessageProcessor;
  EXPECT_CALL(*mock_processor, MockableProcessMessage(_, _))
      .WillOnce(SaveArg<0>(&captured_msg));
  sender_delegate_.set_outgoing_message_processor(
      base::WrapUnique(mock_processor));

  sender_delegate_.DeliverBlob(blob_id_, CreateBlobDataPtr(kBlobPayload));

  EXPECT_EQ(BlobChannelMessage::TypeCase::kTransferBlob,
            captured_msg.blob_channel().type_case());
  EXPECT_EQ(blob_id_, captured_msg.blob_channel().transfer_blob().blob_id());
  EXPECT_EQ(kBlobPayload,
            captured_msg.blob_channel().transfer_blob().payload());
}

// Verifies that the Receiver understands messages sent by the Sender.
TEST_F(HeliumBlobChannelTest, TransferBlobCompatibility) {
  EXPECT_CALL(mock_receiver_,
              OnBlobReceived(blob_id_, BlobDataPtrEqualsString(kBlobPayload)));
  sender_delegate_.DeliverBlob(blob_id_, CreateBlobDataPtr(kBlobPayload));
}

}  // namespace
}  // namespace blimp
