'use strict'

import base64_url_decode from './base64_url_decode'

class InvalidTokenError extends Error {
  message: string

  constructor(message: string) {
    super(message)

    // Set the prototype explicitly.
    Object.setPrototypeOf(this, InvalidTokenError.prototype)

    this.message = message
    this.name = 'InvalidTokenError'
  }
}

interface IOptions {
  header: boolean | undefined
}

const JwtDecode = function (token: string, options: IOptions) {
  if (typeof token !== 'string') {
    throw new InvalidTokenError('Invalid token specified')
  }

  options = options || {}
  var pos = options.header === true ? 0 : 1
  try {
    return JSON.parse(base64_url_decode(token.split('.')[pos]))
  } catch (e) {
    if (e instanceof Error) {
      throw new InvalidTokenError('Invalid token specified: ' + e.message)
    }
  }
}

JwtDecode.InvalidTokenError = InvalidTokenError

export default JwtDecode

