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

#include "chromeos/ash/experiences/arc/touch_selection_menu/touch_selection_menu_runner_chromeos.h"

#include <utility>

#include "ash/session/session_controller_impl.h"
#include "ash/shell.h"
#include "base/functional/bind.h"
#include "base/metrics/user_metrics.h"
#include "base/metrics/user_metrics_action.h"
#include "base/strings/utf_string_conversions.h"
#include "chromeos/ash/experiences/arc/session/arc_bridge_service.h"
#include "chromeos/ash/experiences/arc/session/arc_service_manager.h"
#include "chromeos/ash/experiences/arc/touch_selection_menu/touch_selection_menu_chromeos.h"
#include "components/session_manager/session_manager_types.h"
#include "ui/aura/window.h"
#include "ui/base/clipboard/clipboard.h"
#include "ui/display/display.h"
#include "ui/display/screen.h"
#include "ui/gfx/geometry/rect.h"
#include "ui/gfx/geometry/size.h"

TouchSelectionMenuRunnerChromeOS::TouchSelectionMenuRunnerChromeOS() = default;

TouchSelectionMenuRunnerChromeOS::~TouchSelectionMenuRunnerChromeOS() = default;

void TouchSelectionMenuRunnerChromeOS::OpenMenuWithTextSelectionAction(
    base::WeakPtr<ui::TouchSelectionMenuClient> client,
    const gfx::Rect& anchor_rect,
    const gfx::Size& handle_image_size,
    std::unique_ptr<aura::WindowTracker> tracker,
    bool can_paste,
    std::vector<arc::mojom::TextSelectionActionPtr> actions) {
  if (tracker->windows().empty()) {
    return;
  }
  // The `client` may have been deleted during the mojo call to ARC.
  if (!client) {
    return;
  }

  if (!client->ShouldShowQuickMenu(can_paste)) {
    return;
  }

  arc::mojom::TextSelectionActionPtr top_action;
  // Get the first action generated by the Android TextClassifier.
  for (auto& action : actions) {
    if (!action->text_classifier_action) {
      continue;
    }
    std::swap(top_action, action);
    break;
  }

  // The menu manages its own lifetime and deletes itself when closed.
  TouchSelectionMenuChromeOS* menu = new TouchSelectionMenuChromeOS(
      this, client, tracker->Pop(), std::move(top_action), can_paste);
  ShowMenu(menu, anchor_rect, handle_image_size);
}

bool TouchSelectionMenuRunnerChromeOS::RequestTextSelection(
    base::WeakPtr<ui::TouchSelectionMenuClient> client,
    const gfx::Rect& anchor_rect,
    const gfx::Size& handle_image_size,
    aura::Window* context,
    bool can_paste) {
  DCHECK(client);
  const std::string converted_text =
      base::UTF16ToUTF8(client->GetSelectedText());
  if (converted_text.empty()) {
    return false;
  }

  // Some options like 'Cut' and 'Copy' can be accessed even during login
  // screen, however ARC shouldn't be able to starts apps during that state.
  const ash::SessionControllerImpl* controller =
      ash::Shell::Get()->session_controller();
  if (controller->IsScreenLocked() ||
      controller->GetSessionState() != session_manager::SessionState::ACTIVE) {
    return false;
  }

  auto* arc_service_manager = arc::ArcServiceManager::Get();
  if (!arc_service_manager) {
    return false;
  }

  arc::mojom::IntentHelperInstance* instance = ARC_GET_INSTANCE_FOR_METHOD(
      arc_service_manager->arc_bridge_service()->intent_helper(),
      RequestTextSelectionActions);
  if (!instance) {
    return false;
  }

  // aura::WindowTracker is used since the newly created menu may need to know
  // about the parent window.
  std::unique_ptr<aura::WindowTracker> tracker =
      std::make_unique<aura::WindowTracker>();
  tracker->Add(context);

  const display::Screen* screen = display::Screen::Get();
  DCHECK(screen);

  base::RecordAction(base::UserMetricsAction("Arc.SmartTextSelection.Request"));
  // Fetch actions for selected text and then show quick menu.
  instance->RequestTextSelectionActions(
      converted_text,
      arc::mojom::ScaleFactor(
          screen->GetDisplayNearestWindow(context).device_scale_factor()),
      base::BindOnce(
          &TouchSelectionMenuRunnerChromeOS::OpenMenuWithTextSelectionAction,
          menu_request_weak_ptr_factory_.GetWeakPtr(), client, anchor_rect,
          handle_image_size, std::move(tracker), can_paste));
  return true;
}

void TouchSelectionMenuRunnerChromeOS::CloseMenu() {
  menu_request_weak_ptr_factory_.InvalidateWeakPtrs();
  views::TouchSelectionMenuRunnerViews::CloseMenu();
}

void TouchSelectionMenuRunnerChromeOS::OpenMenu(
    base::WeakPtr<ui::TouchSelectionMenuClient> client,
    const gfx::Rect& anchor_rect,
    const gfx::Size& handle_image_size,
    aura::Window* context,
    bool can_paste) {
  CloseMenu();

  // If there are no commands to show in the menu finish right away.
  // Also if classification is possible delegate creating/showing a
  // new menu.
  if (!IsMenuAvailable(client.get(), can_paste) ||
      RequestTextSelection(client, anchor_rect, handle_image_size, context,
                           can_paste)) {
    return;
  }

  // The menu manages its own lifetime and deletes itself when closed.
  TouchSelectionMenuChromeOS* menu =
      new TouchSelectionMenuChromeOS(this, client, context,
                                     /*action=*/nullptr, can_paste);
  ShowMenu(menu, anchor_rect, handle_image_size);
}
