"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = getLinePos;

function findLineStarts(src) {
  var ls = [0];
  var offset = src.indexOf('\n');

  while (offset !== -1) {
    offset += 1;
    ls.push(offset);
    offset = src.indexOf('\n', offset);
  }

  return ls;
}
/**
 * Determine the line/col position matching a character offset.
 *
 * Accepts a source string or a CST document as the second parameter. With
 * the latter, starting indices for lines are cached in the document as
 * `lineStarts: number[]`.
 *
 * Returns a one-indexed `{ line, col }` location if found, or
 * `undefined` otherwise.
 *
 * @param {number} offset
 * @param {string|Document|Document[]} cst
 * @returns {{ line: number, col: number }|undefined}
 */


function getLinePos(offset, cst) {
  if (typeof offset === 'number' && offset >= 0) {
    var lineStarts, srcLength;

    if (typeof cst === 'string') {
      lineStarts = findLineStarts(cst);
      srcLength = cst.length;
    } else {
      if (Array.isArray(cst)) cst = cst[0];

      if (cst) {
        if (!cst.lineStarts) cst.lineStarts = findLineStarts(cst.context.src);
        lineStarts = cst.lineStarts;
        srcLength = cst.context.src.length;
      }
    }

    if (lineStarts && offset <= srcLength) {
      for (var i = 0; i < lineStarts.length; ++i) {
        var start = lineStarts[i];

        if (offset < start) {
          return {
            line: i,
            col: offset - lineStarts[i - 1] + 1
          };
        }

        if (offset === start) return {
          line: i + 1,
          col: 1
        };
      }

      var line = lineStarts.length;
      return {
        line: line,
        col: offset - lineStarts[line - 1] + 1
      };
    }
  }

  return undefined;
}