import { datadogRum } from "@datadog/browser-rum";
import { useEffect } from "react";
import { matchRoutes, RouteMatch, useLocation } from "react-router-dom";
import { routes } from "../lib/routes";

function computeViewName(routeMatches: RouteMatch[]) {
  let viewName = "";
  for (let index = 0; index < routeMatches.length; index++) {
    const routeMatch = routeMatches[index];
    const path = routeMatch.route.path;
    // Skip pathless routes
    if (!path) {
      continue;
    }

    if (path.startsWith("/")) {
      // Handle absolute child route paths
      viewName = path;
    } else {
      // Handle route paths ending with "/"
      viewName += viewName.endsWith("/") ? path : `/${path}`;
    }
  }

  return viewName || "/";
}

export const useDatadogRumViewName = () => {
  const location = useLocation();

  useEffect(() => {
    const routeMatches = matchRoutes(routes, location.pathname);
    const viewName = routeMatches && computeViewName(routeMatches);
    if (viewName) {
      datadogRum.startView({ name: viewName });
    }
  }, [location.pathname]);
};
