import { base64 } from 'rfc4648'

import { verifyData } from '../../util/crypto/verify'

import { scrypt, userIdSnrp } from '../scrypt/scrypt-selectors'
import { searchTree } from './login'



export function getEmptyStash(username) {
  return {
    username,
    appId: '',
    loginId: new Uint8Array(0),
    pendingVouchers: []
  }
}

/**
 * Finds the login stash for the given username.
 */
export function getStashByUsername(
  ai,
  username
) {
  const { stashes } = ai.props.state.login
  for (const stash of stashes) {
    if (stash.username === username) return stash
  }
}

export function getStashById(ai, loginId) {
  const { stashes } = ai.props.state.login
  for (const stashTree of stashes) {
    const stash = searchTree(stashTree, stash =>
      verifyData(stash.loginId, loginId)
    )
    if (stash != null) return { stashTree, stash }
  }
  throw new Error(`Cannot find stash '${base64.stringify(loginId)}'`)
}

export function getChildStash(
  stashTree,
  loginId
) {
  const stash = searchTree(stashTree, stash =>
    verifyData(stash.loginId, loginId)
  )
  if (stash != null) return stash
  throw new Error(`Cannot find child stash '${base64.stringify(loginId)}'`)
}

// Hashed username cache:
const userIdCache = {}

/**
 * Hashes a username into a userId.
 */
export function hashUsername(
  ai,
  username
) {
  if (userIdCache[username] == null) {
    userIdCache[username] = scrypt(ai, username, userIdSnrp)
  }
  return userIdCache[username]
}
