export default async function getTag(viewer) {
  const tree = viewer.model.getInstanceTree();
  const result = [];
  const tasks = [];

  tree.enumNodeChildren(
    tree.getRootId(),
    (dbId) => {
      tasks.push(
        new Promise((resolve) => {
          viewer.getProperties(dbId, (props) => {
            const tag = props.properties.find((p) =>
              p.displayName.includes("tag_id"),
            );

            if (tag) {
              let currentId = dbId;
              let parentId = tree.getNodeParentId(currentId);

              while (parentId !== tree.getRootId()) {
                currentId = parentId;
                parentId = tree.getNodeParentId(currentId);
              }
              console.log("最上層父節點 ID:", currentId);
              result.push({
                forgeID: dbId,
                tag: tag.displayValue,
                parent: currentId,
              });
            }

            resolve();
          });
        }),
      );
    },
    true,
  );

  await Promise.all(tasks);

  const uniqueResult = [];
  result.forEach((item) => {
    if (!uniqueResult.some((i) => i.tag === item.tag)) {
      uniqueResult.push(item);
    }
  });

  return uniqueResult;
}
