import { findAssignment as f } from "../utils/grammar-utils.js";
import { isReference as i } from "../syntax-tree.js";
import { getDocument as d } from "../utils/ast-utils.js";
import { isChildNode as s, toDocumentSegment as a } from "../utils/cst-utils.js";
import { stream as c } from "../utils/stream.js";
import { UriUtils as m } from "../utils/uri-utils.js";
class A {
  constructor(e) {
    this.nameProvider = e.references.NameProvider, this.index = e.shared.workspace.IndexManager, this.nodeLocator = e.workspace.AstNodeLocator;
  }
  findDeclaration(e) {
    if (e) {
      const t = f(e), r = e.astNode;
      if (t && r) {
        const n = r[t.feature];
        if (i(n))
          return n.ref;
        if (Array.isArray(n)) {
          for (const o of n)
            if (i(o) && o.$refNode && o.$refNode.offset <= e.offset && o.$refNode.end >= e.end)
              return o.ref;
        }
      }
      if (r) {
        const n = this.nameProvider.getNameNode(r);
        if (n && (n === e || s(e, n)))
          return r;
      }
    }
  }
  findDeclarationNode(e) {
    const t = this.findDeclaration(e);
    if (t != null && t.$cstNode) {
      const r = this.nameProvider.getNameNode(t);
      return r ?? t.$cstNode;
    }
  }
  findReferences(e, t) {
    const r = [];
    if (t.includeDeclaration) {
      const o = this.getReferenceToSelf(e);
      o && r.push(o);
    }
    let n = this.index.findAllReferences(e, this.nodeLocator.getAstNodePath(e));
    return t.documentUri && (n = n.filter((o) => m.equals(o.sourceUri, t.documentUri))), r.push(...n), c(r);
  }
  getReferenceToSelf(e) {
    const t = this.nameProvider.getNameNode(e);
    if (t) {
      const r = d(e), n = this.nodeLocator.getAstNodePath(e);
      return {
        sourceUri: r.uri,
        sourcePath: n,
        targetUri: r.uri,
        targetPath: n,
        segment: a(t),
        local: !0
      };
    }
  }
}
export {
  A as DefaultReferences
};
