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

#include <memory>
#include <string>

#include "base/memory/raw_ptr.h"
#include "base/strings/string_util.h"
#include "base/strings/utf_string_conversions.h"
#include "base/test/scoped_feature_list.h"
#include "chrome/browser/ui/browser_window/public/browser_window_features.h"
#include "chrome/browser/ui/browser_window/public/browser_window_interface.h"
#include "chrome/browser/ui/dialogs/browser_dialogs.h"
#include "chrome/browser/ui/exclusive_access/exclusive_access_manager.h"
#include "chrome/browser/ui/exclusive_access/fullscreen_controller.h"
#include "chrome/browser/ui/navigator/browser_navigator_params.h"
#include "chrome/browser/ui/tabs/split_tab_metrics.h"
#include "chrome/browser/ui/tabs/tab_strip_model.h"
#include "chrome/browser/ui/test/test_browser_dialog.h"
#include "chrome/browser/ui/ui_features.h"
#include "chrome/browser/ui/views/extensions/chooser_dialog_view.h"
#include "chrome/browser/ui/views/frame/browser_view.h"
#include "chrome/browser/ui/views/frame/contents_container_outline.h"
#include "chrome/browser/ui/views/frame/contents_container_view.h"
#include "chrome/browser/ui/views/frame/multi_contents_view.h"
#include "chrome/test/base/in_process_browser_test.h"
#include "chrome/test/base/ui_test_utils.h"
#include "components/constrained_window/constrained_window_views.h"
#include "components/permissions/fake_bluetooth_chooser_controller.h"
#include "components/permissions/fake_usb_chooser_controller.h"
#include "components/split_tabs/split_tab_visual_data.h"
#include "content/public/test/browser_test.h"
#include "content/public/test/browser_test_utils.h"
#include "net/dns/mock_host_resolver.h"
#include "net/test/embedded_test_server/embedded_test_server.h"
#include "ui/base/page_transition_types.h"

namespace {

void ShowChooserBubble(
    BrowserWindowInterface* browser,
    std::unique_ptr<permissions::ChooserController> controller) {
  auto* contents = browser->GetTabStripModel()->GetActiveWebContents();
  chrome::ShowDeviceChooserDialog(contents->GetPrimaryMainFrame(),
                                  std::move(controller));
}

void ShowChooserModal(
    BrowserWindowInterface* browser,
    std::unique_ptr<permissions::ChooserController> controller) {
  auto* web_contents = browser->GetTabStripModel()->GetActiveWebContents();
  constrained_window::ShowWebModalDialogViews(
      new ChooserDialogView(std::move(controller)), web_contents);
}

void ShowChooser(const std::string& test_name,
                 BrowserWindowInterface* browser,
                 std::unique_ptr<permissions::ChooserController> controller) {
  if (base::EndsWith(test_name, "Modal", base::CompareCase::SENSITIVE)) {
    ShowChooserModal(browser, std::move(controller));
  } else {
    ShowChooserBubble(browser, std::move(controller));
  }
}

}  // namespace

// Invokes a dialog allowing the user to select a USB device for a web page or
// extension.
class UsbChooserBrowserTest : public DialogBrowserTest {
 public:
  UsbChooserBrowserTest() = default;

  UsbChooserBrowserTest(const UsbChooserBrowserTest&) = delete;
  UsbChooserBrowserTest& operator=(const UsbChooserBrowserTest&) = delete;

  // DialogBrowserTest:
  void ShowUi(const std::string& name) override {
    ShowChooser(name, browser(),
                std::make_unique<FakeUsbChooserController>(device_count_));
  }

 protected:
  // Number of devices to show in the chooser.
  int device_count_ = 0;
};

IN_PROC_BROWSER_TEST_F(UsbChooserBrowserTest, InvokeUi_NoDevicesBubble) {
  ShowAndVerifyUi();
}

IN_PROC_BROWSER_TEST_F(UsbChooserBrowserTest, InvokeUi_NoDevicesModal) {
  ShowAndVerifyUi();
}

IN_PROC_BROWSER_TEST_F(UsbChooserBrowserTest, InvokeUi_WithDevicesBubble) {
  device_count_ = 5;
  ShowAndVerifyUi();
}

IN_PROC_BROWSER_TEST_F(UsbChooserBrowserTest, InvokeUi_WithDevicesModal) {
  device_count_ = 5;
  ShowAndVerifyUi();
}

// Invokes a dialog allowing the user to select a Bluetooth device for a web
// page or extension.
class BluetoothChooserBrowserTest : public DialogBrowserTest {
 public:
  BluetoothChooserBrowserTest() = default;

  BluetoothChooserBrowserTest(const BluetoothChooserBrowserTest&) = delete;
  BluetoothChooserBrowserTest& operator=(const BluetoothChooserBrowserTest&) =
      delete;

  // DialogBrowserTest:
  void ShowUi(const std::string& name) override {
    auto controller =
        std::make_unique<permissions::FakeBluetoothChooserController>(
            std::move(devices_));
    auto* controller_unowned = controller.get();
    ShowChooser(name, browser(), std::move(controller));
    controller_unowned->SetBluetoothStatus(status_);
  }

  void set_status(
      permissions::FakeBluetoothChooserController::BluetoothStatus status) {
    status_ = status;
  }

  void AddDeviceForAllStrengths() {
    devices_.push_back(
        {"Device with Strength 0",
         permissions::FakeBluetoothChooserController::NOT_CONNECTED,
         permissions::FakeBluetoothChooserController::NOT_PAIRED,
         permissions::FakeBluetoothChooserController::kSignalStrengthLevel0});
    devices_.push_back(
        {"Device with Strength 1",
         permissions::FakeBluetoothChooserController::NOT_CONNECTED,
         permissions::FakeBluetoothChooserController::NOT_PAIRED,
         permissions::FakeBluetoothChooserController::kSignalStrengthLevel1});
    devices_.push_back(
        {"Device with Strength 2",
         permissions::FakeBluetoothChooserController::NOT_CONNECTED,
         permissions::FakeBluetoothChooserController::NOT_PAIRED,
         permissions::FakeBluetoothChooserController::kSignalStrengthLevel2});
    devices_.push_back(
        {"Device with Strength 3",
         permissions::FakeBluetoothChooserController::NOT_CONNECTED,
         permissions::FakeBluetoothChooserController::NOT_PAIRED,
         permissions::FakeBluetoothChooserController::kSignalStrengthLevel3});
    devices_.push_back(
        {"Device with Strength 4",
         permissions::FakeBluetoothChooserController::NOT_CONNECTED,
         permissions::FakeBluetoothChooserController::NOT_PAIRED,
         permissions::FakeBluetoothChooserController::kSignalStrengthLevel4});
  }

  void AddConnectedDevice() {
    devices_.push_back(
        {"Connected Device",
         permissions::FakeBluetoothChooserController::CONNECTED,
         permissions::FakeBluetoothChooserController::NOT_PAIRED,
         permissions::FakeBluetoothChooserController::kSignalStrengthLevel4});
  }

  void AddPairedDevice() {
    devices_.push_back(
        {"Paired Device",
         permissions::FakeBluetoothChooserController::NOT_CONNECTED,
         permissions::FakeBluetoothChooserController::PAIRED,
         permissions::FakeBluetoothChooserController::kSignalStrengthLevel4});
  }

 private:
  permissions::FakeBluetoothChooserController::BluetoothStatus status_ =
      permissions::FakeBluetoothChooserController::BluetoothStatus::UNAVAILABLE;
  std::vector<permissions::FakeBluetoothChooserController::FakeDevice> devices_;
};

IN_PROC_BROWSER_TEST_F(BluetoothChooserBrowserTest,
                       InvokeUi_UnavailableBubble) {
  ShowAndVerifyUi();
}

IN_PROC_BROWSER_TEST_F(BluetoothChooserBrowserTest, InvokeUi_UnavailableModal) {
  ShowAndVerifyUi();
}

IN_PROC_BROWSER_TEST_F(BluetoothChooserBrowserTest, InvokeUi_NoDevicesBubble) {
  set_status(
      permissions::FakeBluetoothChooserController::BluetoothStatus::IDLE);
  ShowAndVerifyUi();
}

IN_PROC_BROWSER_TEST_F(BluetoothChooserBrowserTest, InvokeUi_NoDevicesModal) {
  set_status(
      permissions::FakeBluetoothChooserController::BluetoothStatus::IDLE);
  ShowAndVerifyUi();
}

IN_PROC_BROWSER_TEST_F(BluetoothChooserBrowserTest, InvokeUi_ScanningBubble) {
  set_status(
      permissions::FakeBluetoothChooserController::BluetoothStatus::SCANNING);
  ShowAndVerifyUi();
}

IN_PROC_BROWSER_TEST_F(BluetoothChooserBrowserTest, InvokeUi_ScanningModal) {
  set_status(
      permissions::FakeBluetoothChooserController::BluetoothStatus::SCANNING);
  ShowAndVerifyUi();
}

IN_PROC_BROWSER_TEST_F(BluetoothChooserBrowserTest,
                       InvokeUi_ScanningWithDevicesBubble) {
  set_status(
      permissions::FakeBluetoothChooserController::BluetoothStatus::SCANNING);
  AddDeviceForAllStrengths();
  ShowAndVerifyUi();
}

IN_PROC_BROWSER_TEST_F(BluetoothChooserBrowserTest,
                       InvokeUi_ScanningWithDevicesModal) {
  set_status(
      permissions::FakeBluetoothChooserController::BluetoothStatus::SCANNING);
  AddDeviceForAllStrengths();
  ShowAndVerifyUi();
}

IN_PROC_BROWSER_TEST_F(BluetoothChooserBrowserTest, InvokeUi_ConnectedBubble) {
  set_status(
      permissions::FakeBluetoothChooserController::BluetoothStatus::IDLE);
  AddConnectedDevice();
  ShowAndVerifyUi();
}

IN_PROC_BROWSER_TEST_F(BluetoothChooserBrowserTest, InvokeUi_ConnectedModal) {
  set_status(
      permissions::FakeBluetoothChooserController::BluetoothStatus::IDLE);
  AddConnectedDevice();
  ShowAndVerifyUi();
}

IN_PROC_BROWSER_TEST_F(BluetoothChooserBrowserTest, InvokeUi_PairedBubble) {
  set_status(
      permissions::FakeBluetoothChooserController::BluetoothStatus::IDLE);
  AddPairedDevice();
  ShowAndVerifyUi();
}

IN_PROC_BROWSER_TEST_F(BluetoothChooserBrowserTest, InvokeUi_PairedModal) {
  set_status(
      permissions::FakeBluetoothChooserController::BluetoothStatus::IDLE);
  AddPairedDevice();
  ShowAndVerifyUi();
}

class DeviceChooserBubbleTest : public InProcessBrowserTest {
 public:
  void SetUpOnMainThread() override {
    host_resolver()->AddRule("*", "127.0.0.1");
    ASSERT_TRUE(embedded_test_server()->Start());
    InProcessBrowserTest::SetUpOnMainThread();
  }

  GURL GetURL(const char* hostname) const {
    return embedded_test_server()->GetURL(hostname, "/title1.html");
  }
};

IN_PROC_BROWSER_TEST_F(DeviceChooserBubbleTest,
                       ShowDeviceChooserDialogInSplitView) {
  ASSERT_TRUE(AddTabAtIndex(0, GetURL("example.com"),
                            ui::PageTransition::PAGE_TRANSITION_TYPED));
  TabStripModel* const tab_strip_model = browser()->GetTabStripModel();
  tab_strip_model->ActivateTabAt(0);
  tab_strip_model->AddToNewSplit(
      {1}, split_tabs::SplitTabVisualData(),
      split_tabs::SplitTabCreatedSource::kToolbarButton);

  std::vector<raw_ptr<ContentsContainerView, DanglingUntriaged>>
      contents_container_views =
          BrowserView::GetBrowserViewForBrowser(browser())
              ->multi_contents_view()
              ->contents_container_views();
  ASSERT_EQ(contents_container_views.size(), 2U);
  EXPECT_FALSE(
      contents_container_views[0]->contents_outline_view()->is_highlighted());
  EXPECT_FALSE(
      contents_container_views[1]->contents_outline_view()->is_highlighted());

  ShowChooserBubble(browser(), std::make_unique<FakeUsbChooserController>(0));

  EXPECT_TRUE(
      contents_container_views[0]->contents_outline_view()->is_highlighted());
  EXPECT_FALSE(
      contents_container_views[1]->contents_outline_view()->is_highlighted());
}

IN_PROC_BROWSER_TEST_F(DeviceChooserBubbleTest,
                       ChooserBubblePreventsFullscreen) {
  ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), GetURL("example.com")));

  ShowChooserBubble(browser(), std::make_unique<FakeUsbChooserController>(0));

  content::WebContents* web_contents =
      browser()->GetTabStripModel()->GetActiveWebContents();
  FullscreenController* fullscreen_controller = browser()
                                                    ->GetFeatures()
                                                    .exclusive_access_manager()
                                                    ->fullscreen_controller();

  // While bubble is showing, tab fullscreen cannot be entered.
  EXPECT_FALSE(content::ExecJs(web_contents,
                               "document.documentElement.requestFullscreen()"));
  EXPECT_FALSE(fullscreen_controller->IsTabFullscreen());
}
