import parseNpmTarballUrl from 'parse-npm-tarball-url'
import getVersionSelectorType = require('version-selector-type')

export interface RegistryPackageSpec {
  type: 'tag' | 'version' | 'range',
  name: string,
  fetchSpec: string,
  normalizedPref?: string,
}

export default function parsePref (
  pref: string,
  alias: string | undefined,
  defaultTag: string,
  registry: string,
): RegistryPackageSpec | null {
  let name = alias
  if (pref.startsWith('npm:')) {
    pref = pref.substr(4)
    const index = pref.lastIndexOf('@')
    if (index < 1) {
      name = pref
      pref = defaultTag
    } else {
      name = pref.substr(0, index)
      pref = pref.substr(index + 1)
    }
  }
  if (name) {
    const selector = getVersionSelectorType(pref)
    if (selector) {
      return {
        fetchSpec: selector.normalized,
        name,
        type: selector.type,
      }
    }
  }
  if (pref.startsWith(registry)) {
    const pkg = parseNpmTarballUrl(pref)
    if (pkg) {
      return {
        fetchSpec: pkg.version,
        name: pkg.name,
        normalizedPref: pref,
        type: 'version',
      }
    }
  }
  return null
}
