#!/usr/bin/env node

var bsv = require('bsv')
var Peer = require('bitcore-p2p-cash').Peer;
var Messages = require('bitcore-p2p-cash').Messages;
var express = require('express')
var app = express()
var program = require('commander')
var version = require('./package.json').version
var bodyParser = require('body-parser')

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));


program
    .version(version)
    .option('-p, --peer [ip]', 'IP address of peer, find it on bitsonar', '139.196.32.192')
    
program
    .parse(process.argv)

var bsvMessages = new Messages({Block: bsv.Block, 
                                BlockHeader: bsv.BlockHeader,
                                Transaction: bsv.Transaction,
                                MerkleBlock: bsv.MerkleBlock
                               })
var peer = new Peer({host: program.peer, messages: bsvMessages})

app.post('/', function(req, res){
    handle(req, res)
})

async function handle(req, res){
    var tx = bsv.Transaction(req.body.hex)
    console.log('Broadcasting ' + tx.id)
    var msg = peer.messages.Transaction(tx)
    peer.sendMessage(msg)
    res.send(tx.id+ " broadcasted")
}

var Type = [
    'Error',
    'Transaction',
    'Block',
    'Filtered Block',
    'Cmpct Block'
]

peer.on('ready', function() {
  // peer info
  console.log(peer.version, peer.subversion, peer.bestHeight)
  console.log('Peer Address: ' + program.peer)
  app.listen(8000, function(){console.log('QuickAPI is listening on 8000')})
})

peer.on('inv', function(message) {
    console.log('inv message')
    message.inventory.forEach(function(item){
        console.log('Item type:' + Type[item.type] + ' hash:' + item.hash.reverse().toString('hex'))
    })
    this.sendMessage(this.messages.GetData(message.inventory))
})


peer.on('reject', function(message) {
    console.log('Peer reject')
    console.log(message)
});

peer.on('disconnect', function() {
  console.log('connection closed')
})

peer.on('error', function(e) {
  console.log(e)
  console.log('connection lost')
})

peer.connect()