/**
 * Created by paul on 8/26/17.
 * 
 */

import crypto from 'crypto'
import { validate } from 'jsonschema'
import secp256k1 from 'secp256k1'

export function validateObject(object, schema) {
  let result = null
  try {
    result = validate(object, schema)
  } catch (e) {
    return false
  }

  return result && result.errors && result.errors.length === 0
}

export async function hash256(hex) {
  return Promise.resolve(hash256Sync(hex))
}

export async function secp256k1Sign(message, key) {
  const sigObj = await secp256k1.sign(message, key)
  return sigObj
}

export function hash256Sync(hex) {
  return crypto.createHash('sha256').update(hex).digest()
}

export async function hash160(hex) {
  return Promise.resolve(
    crypto
      .createHash('ripemd160')
      .update(await hash256(hex))
      .digest()
  )
}

export function reverseBufferToHex(rawBuffer) {
  return rawBuffer.toString('hex').match(/../g).reverse().join('')
}

/**
 * Waits for the first successful promise.
 * If no promise succeeds, returns the last failure.
 */
export function promiseAny(promises) {
  return new Promise((resolve, reject) => {
    let pending = promises.length
    for (const promise of promises) {
      promise.then(
        value => resolve(value),
        error => --pending || reject(error)
      )
    }
  })
}
