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

#include "chrome/browser/page_load_metrics/observers/chrome_gws_page_load_metrics_observer.h"

#include <string>

#include "chrome/browser/after_startup_task_utils.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/signin/identity_manager_factory.h"
#include "chrome/common/webui_url_constants.h"
#include "components/signin/public/identity_manager/identity_manager.h"
#include "content/public/browser/browser_context.h"
#include "content/public/browser/navigation_handle.h"
#include "content/public/browser/security_principal.h"
#include "content/public/browser/site_instance.h"
#include "content/public/browser/web_contents.h"

ChromeGWSPageLoadMetricsObserver::ChromeGWSPageLoadMetricsObserver() = default;

bool ChromeGWSPageLoadMetricsObserver::IsFromNewTabPage(
    content::NavigationHandle* navigation_handle) {
  auto* start_instance = navigation_handle->GetStartingSiteInstance();
  if (!start_instance) {
    return false;
  }

  auto& principal = start_instance->GetSecurityPrincipal();
  const GURL& ntp_url = chrome::ChromeUINewTabPageURLAsGURL();

  return principal.SchemeIs(ntp_url.scheme()) &&
         principal.GetHost() == ntp_url.host();
}

bool ChromeGWSPageLoadMetricsObserver::IsBrowserStartupComplete() {
  return AfterStartupTaskUtils::IsBrowserStartupComplete();
}

bool ChromeGWSPageLoadMetricsObserver::IsIncognitoProfile() const {
  if (Profile* profile = Profile::FromBrowserContext(
          GetDelegate().GetWebContents()->GetBrowserContext())) {
    return profile->IsIncognitoProfile();
  }
  return false;
}

bool ChromeGWSPageLoadMetricsObserver::IsSignedIn(
    content::BrowserContext* browser_context) const {
  signin::IdentityManager* identity_manager =
      IdentityManagerFactory::GetForProfile(
          Profile::FromBrowserContext(browser_context));
  return identity_manager &&
         !identity_manager->GetAccountsWithRefreshTokens().empty();
}

content::BrowserContext*
ChromeGWSPageLoadMetricsObserver::GetOriginalBrowserContext() {
  if (Profile* profile = Profile::FromBrowserContext(
          GetDelegate().GetWebContents()->GetBrowserContext())) {
    return profile->GetOriginalProfile();
  }
  return nullptr;
}
