const chalk = require('chalk')
const util = require('./util')

const contractPath = '../Contracts/Conference.sol'
const contractName = 'Conference'
const me = '0xB82C0ECcf0F5b8c02353358F28662f5AF2567686'
const password = ''

function unlockAccount () {
  return util.unlockAccount(me, password)
}

function readContract () {
  return util.readContract(contractPath)
}

function compileContract (source) {
  return util.compileContract(contractName, source)
}

function estimateGas (contract) {
  return util.estimateGas(contract)
}

function deploy (contract) {
  return util.deployContract(contract, me)
}

function done () {
  console.log('Done')
  process.exit(0)
}

function handleError (err) {
  console.error(chalk.red(err))
  process.exit(-1)
}

unlockAccount()
  .then(readContract)
  .then(compileContract)
  .then(estimateGas)
  .then(deploy)
  .then(done)
.catch(handleError)

const program = require('commander')
const chalk = require('chalk')
const lib = require('./lib')

const contractPath = '../Contracts/Conference.sol'
const contractName = 'Conference'

function estimateGas (contract) {
  return new Promise(function (resolve, reject) {
    lib.web3.eth.estimateGas({data: contract.byteCode}, function (err, gas) {
      if (err) {
        console.error(chalk.red('Failed to estimate gas'))
        return reject(err)
      }
      contract.gasEstimate = gas * 4
      console.log('Estimated gas to be:', contract.gasEstimate)
      resolve(contract)
    })
  })
}

function deploy (address) {
  return function (contract) {
    var params = {
      from: address,
      data: contract.byteCode,
      gas: contract.gasEstimate
    }
    return new Promise(function (resolve, reject) {
      contract.new(params, function (err, deployed) {
        if (err) {
          console.error(chalk.red('Failed to deploy contract'))
          return reject(err)
        }

        if (!deployed.address) {
          console.log('Sent transaction with hash:', deployed.transactionHash)
          console.log('Waiting for transaction to be mined')
        } else {
          console.log(chalk.green('Contract mined at address:', deployed.address))
          resolve(deployed)
        }
      })
    })
  }
}

function deployContract (organizer, password) {
  password = password || ''
  lib.unlockAccount(organizer, password)
    .then(lib.readContract(contractPath))
    .then(lib.compileContract(contractName))
    .then(estimateGas)
    .then(deploy(organizer))
    .then(lib.done)
  .catch(lib.handleError)
}

program
  .arguments('address')
  .option('-p', '--password', 'Password of the account')
  .description('Deploy contract')
  .action(deployContract)
  .parse(process.argv)

clean up and command line args