'use strict'

var util = require('util')
var progress = require('progress-string')
var diff = require('ansi-diff-stream')()
var speedometer = require('speedometer')
var prettierBytes = require('prettier-bytes')
var Updater = require('../updater')
var debug = require('debug')(require('../package').name)

module.exports = function (db, opts) {
  var downloadByteSpeed = speedometer()
  var downloadBlockSpeed = speedometer()
  var processingSpeed = speedometer()
  var updater = new Updater(db, opts)
  var lastFeedLength = 0
  var downloaded = 0
  var remaining = 0
  var bps = 0
  var pkgps = 0
  var pps = 0

  updater
    .on('init', trackSyncing)
    .on('running', function () {
      lastFeedLength = updater.feed.length
      remaining = updater.blocksRemaining()
    })
    .on('processed', function () {
      pps = processingSpeed(1)
    })
    .on('end', function () {
      printProgress()
      process.exit(updater.live ? 1 : 0)
    })
    .on('error', function (err) {
      throw err
    })

  if (!debug.enabled) diff.pipe(process.stdout)

  function trackSyncing () {
    updater.feed.on('download', function (index, data) {
      bps = downloadByteSpeed(data.length)
      pkgps = downloadBlockSpeed(1)
      downloaded++
      if (updater.feed.length > lastFeedLength) {
        remaining += updater.feed.length - lastFeedLength
        lastFeedLength = updater.feed.length
        debug('feed.length changed')
      }
    })

    setInterval(function () {
      bps = downloadByteSpeed(0)
      pkgps = downloadBlockSpeed(0)
      pps = processingSpeed(0)
    }, 1000).unref()

    setInterval(printProgress, 250).unref()
  }

  function printProgress () {
    var processedCounter = updater.processed - updater.startBlock + 1

    if (updater.live) {
      diff.write(
        util.format('downloaded %d [%s pkg/s, %s/s]\n', downloaded, pkgps.toFixed(1), prettierBytes(bps)) +
        util.format('processed  %d [%s pkg/s]', processedCounter, pps.toFixed(1))
      )
    } else {
      var totalToProcess = updater.feed.length - updater.startBlock
      var sessionBar = progress({total: remaining})
      var processedBar = progress({total: totalToProcess})

      diff.write(
        util.format('downloading [%s] (%d/%d) %s pkg/s, %s/s\n', sessionBar(downloaded), downloaded, remaining, pkgps.toFixed(1), prettierBytes(bps)) +
        util.format('processing  [%s] (%d/%d) %s pkg/s', processedBar(processedCounter), processedCounter, totalToProcess, pps.toFixed(1))
      )
    }
  }
}

@@ -1239,22 +1239,24 @@
 d++%0A    
-  if (
+%7D)%0A%0A    
 updater.
@@ -1264,37 +1264,70 @@
 eed.
-length %3E lastFeedL
+on('append', function () %7B%0A      debug('feed.l
 ength
-) %7B%0A  
+ changed')%0A
     
@@ -1380,26 +1380,24 @@
 ength%0A      
-  
 lastFeedLeng
@@ -1425,53 +1425,8 @@
 gth%0A
-        debug('feed.length changed')%0A      %7D%0A
     

Improve feed.length change detection logic