const readline = require('readline')
const fs = require('fs')
const bip39 = require('bip39')
const bsk = require('.')
const crypto = require('crypto')

const inFile = '/home/aaron/devel/onename-spin-down/data/names_to_issue'
const outFile = '/home/aaron/devel/onename-spin-down/data/names_and_keys.json'

function makeOwnerKeyAndSeed(name) {
  const mnemonic = bip39.generateMnemonic(128, crypto.randomBytes)
  const seed = bip39.mnemonicToSeed(mnemonic)
  const ownerHDNode = bsk.BlockstackWallet.fromSeedBuffer(seed)
        .getIdentityAddressNode(0)
  const ownerKey = bsk.ecPairToHexString(ownerHDNode.keyPair)
  const ownerAddress = ownerHDNode.getAddress()
  return { name,
           mnemonic,
           ownerKey,
           ownerAddress }
}


function loadAllAndProcess() {
  const rl = readline.createInterface({
    input: fs.createReadStream(inFile),
    crlfDelay: Infinity
  })

  entries = []

  rl
    .on('line', (line) => {
      if (line) {
        const name = line.slice(0, line.indexOf(','))
        const entry = makeOwnerKeyAndSeed(name)
        entries.push(entry)
      }
    })
    .on('close', () => {
      fs.writeFileSync(outFile, JSON.stringify(
        entries, undefined, 2))
    })
}


loadAllAndProcess()
