var test = require('tape')
var hash = require('.')
var crypto = require('crypto')
var fs = require('fs')
var pull = require('pull-stream')
var toPull = require('stream-to-pull-stream')
var multicb = require('multicb')
var path = require('path')
var gitHash = require('./ext/git')
var ssbHash = require('./ext/ssb')

function hashFile(filename, type, encoding, cb) {
  var shasum = crypto.createHash(type)
  fs.createReadStream(filename).on('data', function (d) {
    shasum.update(d)
  })
  .on('error', cb)
  .on('end', function () {
    cb(null, shasum.digest(encoding))
  })
}

function hashFilePull(filename, type, encoding, cb) {
  pull(
    toPull(fs.createReadStream(filename)),
    hash(type, encoding, cb),
    pull.drain()
  )
}

test('hash a file', function (t) {
  var done = multicb({ pluck: 1, spread: true })
  hashFile(__filename, 'md5', 'hex', done())
  hashFilePull(__filename, 'md5', 'hex', done())
  done(function (err, digestNodejs, digestPull) {
    t.error(err, 'hashes')
    t.equals(digestPull, digestNodejs, 'hash')
    t.end()
  })
})

test('git object hash', function (t) {
  pull(
    pull.once('asdf\n'),
    gitHash({type: 'blob', size: 5}, function (err, digest) {
      t.error(err, 'git hash')
      t.equals(digest, '8bd6648ed130ac9ece0f89cd9a8fbbfd2608427a', 'hash')
      t.end()
    }),
    pull.drain()
  )
})

test('ssb blob id', function (t) {
  var emptyId = '&47DEQpj8HBSa+/TImW+5JCeuQeRkm5NMpJWZG3hSuFU=.sha256'
  pull(
    pull.empty(),
    ssbHash(function (err, digest) {
      t.error(err, 'ssb hash')
      t.equals(digest, emptyId, 'blob id')
      t.end()
    }),
    pull.drain()
  )
})
