import { normalizeScanPath } from "../../comm/path";
export const VIEWS_RESCAN_EVENT = "vome:views-rescan";
const viewMap = new Map;
function rebuildViewMap(files) {
  viewMap.clear();
  for (const [file, loader] of Object.entries(files)) {
    const norm = normalizeScanPath(file);
    if (norm.includes("/components/"))
      continue;
    const m = norm.match(/modules\/.+\.vue$/);
    if (!m)
      continue;
    const rel = m[0].replace(/\.vue$/, "").replace(/\/index$/, "");
    viewMap.set(rel, loader);
  }
}
export function registerViews(files) {
  rebuildViewMap(files);
  if (typeof window !== "undefined") {
    window.dispatchEvent(new CustomEvent(VIEWS_RESCAN_EVENT));
  }
}
export function resolveView(viewPath) {
  if (!viewPath)
    return;
  const normalized = normalizeScanPath(viewPath).replace(/^\/+/, "").replace(/\.vue$/, "").replace(/\/index$/, "");
  return viewMap.get(normalized) || viewMap.get(`modules/${normalized.replace(/^modules\//, "")}`);
}
export function viewPathToName(viewPath) {
  if (!viewPath)
    return;
  const normalized = normalizeScanPath(viewPath).replace(/^\/+/, "").replace(/\.vue$/, "").replace(/\/index$/, "");
  const m = normalized.match(/^(?:modules\/)?([^/]+)\/views\/(.+)$/);
  if (m)
    return `${m[1]}-${m[2].replace(/\//g, "-")}`;
  return;
}
export function listViews() {
  return [...viewMap.keys()].sort();
}
export function listViewsTree() {
  const root = [];
  for (const full of listViews()) {
    const parts = full.replace(/^modules\//, "").split("/").filter(Boolean);
    if (!parts.length)
      continue;
    let level = root;
    let acc = "modules";
    for (let i = 0;i < parts.length; i++) {
      const label = parts[i];
      acc += `/${label}`;
      const isLeaf = i === parts.length - 1;
      let node = level.find((n) => n.label === label);
      if (!node) {
        node = {
          label,
          value: isLeaf ? full : acc,
          isLeaf,
          children: isLeaf ? undefined : []
        };
        level.push(node);
      } else if (isLeaf) {
        node.isLeaf = true;
        node.value = full;
        node.children = undefined;
      }
      if (!isLeaf) {
        if (!node.children)
          node.children = [];
        level = node.children;
      }
    }
  }
  const sortTree = (nodes) => {
    nodes.sort((a, b) => {
      if (!!a.isLeaf !== !!b.isLeaf)
        return a.isLeaf ? 1 : -1;
      return a.label.localeCompare(b.label);
    });
    for (const n of nodes) {
      if (n.children?.length)
        sortTree(n.children);
    }
  };
  sortTree(root);
  return root;
}
