/*
 * Copyright 2022 Google LLC
 *
 * 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
 *
 *     https://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.
 */

import {onTTFB as unattributedOnTTFB} from '../onTTFB.js';
import type {
  TTFBMetric,
  TTFBMetricWithAttribution,
  AttributionReportOpts,
  TTFBAttribution,
} from '../types.js';

const attributeTTFB = (metric: TTFBMetric): TTFBMetricWithAttribution => {
  const navigationEntry = metric.entries[0];
  // Use a default object if no other attribution has been set.
  let attribution: TTFBAttribution = {
    waitingDuration: 0,
    cacheDuration: 0,
    dnsDuration: 0,
    connectionDuration: 0,
    requestDuration: 0,
    // There should only be one instance per TTFB metric
    navigationEntry: navigationEntry,
  };

  if (metric.entries.length) {
    // If it's the hard nav, then can give attribution.
    // Otherwise it's 0 so the defaults are fine.
    if (navigationEntry instanceof PerformanceNavigationTiming) {
      const activationStart = navigationEntry.activationStart || 0;

      // Measure from workerStart or fetchStart so any service worker startup
      // time is included in cacheDuration (which also includes other sw time
      // anyway, that cannot be accurately split out cross-browser).
      const waitEnd = Math.max(
        (navigationEntry.workerStart || navigationEntry.fetchStart || 0) -
          activationStart,
        0,
      );
      const dnsStart = Math.max(
        navigationEntry.domainLookupStart - activationStart,
        0,
      );
      const connectStart = Math.max(
        navigationEntry.connectStart - activationStart,
        0,
      );
      const connectEnd = Math.max(
        navigationEntry.connectEnd - activationStart,
        0,
      );

      attribution = {
        waitingDuration: waitEnd,
        cacheDuration: dnsStart - waitEnd,
        // dnsEnd usually equals connectStart but use connectStart over dnsEnd
        // for dnsDuration in case there ever is a gap.
        dnsDuration: connectStart - dnsStart,
        connectionDuration: connectEnd - connectStart,
        // There is often a gap between connectEnd and requestStart. Attribute
        // that to requestDuration so connectionDuration remains 0 for
        // service worker controlled requests were connectStart and connectEnd
        // are the same.
        requestDuration: metric.value - connectEnd,
        navigationEntry: navigationEntry,
      };
    }
  }

  // Use `Object.assign()` to ensure the original metric object is returned.
  const metricWithAttribution: TTFBMetricWithAttribution = Object.assign(
    metric,
    {attribution},
  );
  return metricWithAttribution;
};

/**
 * Calculates the [TTFB](https://web.dev/articles/ttfb) value for the
 * current page and calls the `callback` function once the page has loaded,
 * along with the relevant `navigation` performance entry used to determine the
 * value. The reported value is a `DOMHighResTimeStamp`.
 *
 * Note, this function waits until after the page is loaded to call `callback`
 * in order to ensure all properties of the `navigation` entry are populated.
 * This is useful if you want to report on other metrics exposed by the
 * [Navigation Timing API](https://w3c.github.io/navigation-timing/). For
 * example, the TTFB metric starts from the page's [time
 * origin](https://www.w3.org/TR/hr-time-2/#sec-time-origin), which means it
 * includes time spent on DNS lookup, connection negotiation, network latency,
 * and server processing time.
 */
export const onTTFB = (
  onReport: (metric: TTFBMetricWithAttribution) => void,
  opts: AttributionReportOpts = {},
) => {
  unattributedOnTTFB((metric: TTFBMetric) => {
    onReport(attributeTTFB(metric));
  }, opts);
};
