// @flow
export function getLabelFromPath(path: *, t: *) {
  return getIdentifierName(path, t)
}

function getDeclaratorName(path, t) {
  // $FlowFixMe
  const parent = path.findParent(p => p.isVariableDeclarator())
  return parent && t.isIdentifier(parent.node.id) ? parent.node.id.name : ''
}

function getIdentifierName(path, t) {
  let classOrClassPropertyParent

  if (
    t.isObjectProperty(path.parentPath) &&
    path.parentPath.node.computed === false &&
    (t.isIdentifier(path.parentPath.node.key) ||
      t.isStringLiteral(path.parentPath.node.key))
  ) {
    return path.parentPath.node.key.name || path.parentPath.node.key.value
  }

  if (path) {
    // $FlowFixMe
    classOrClassPropertyParent = path.findParent(
      p => t.isClassProperty(p) || t.isClass(p)
    )
  }
  if (classOrClassPropertyParent) {
    if (
      t.isClassProperty(classOrClassPropertyParent) &&
      classOrClassPropertyParent.node.computed === false &&
      t.isIdentifier(classOrClassPropertyParent.node.key)
    ) {
      return classOrClassPropertyParent.node.key.name
    }
    if (
      t.isClass(classOrClassPropertyParent) &&
      classOrClassPropertyParent.node.id
    ) {
      return t.isIdentifier(classOrClassPropertyParent.node.id)
        ? classOrClassPropertyParent.node.id.name
        : ''
    }
  }

  let declaratorName = getDeclaratorName(path, t)
  // if the name starts with _ it was probably generated by babel so we should ignore it
  if (declaratorName.charAt(0) === '_') {
    return ''
  }
  return declaratorName
}
