import forEach from 'lodash.foreach'

function listener (status) {
  let nSuccess = 0
  let nCalls = 0

  // Backup status for each vm
  forEach(status.calls, call => {
    let vmStatus

    if (call.error) {
      vmStatus = 'Fail'
    } else {
      nSuccess++
      vmStatus = 'Success'
    }

    nCalls++

    const vm = this._xo.getObject(call.params.id)

    console.log(
      `VM Name: ${vm.name_label}
      UUID: ${call.params.id}
      Status: ${vmStatus}
      Start time: ${call.start}
      End time: ${call.end}
      Duration: ${call.end - call.start}
      `
    )
  })

  const globalStatus = nSuccess === nCalls
        ? 'Success'
        : 'Fail'

  // Global status
  console.log(
    `Global status: ${globalStatus}
    Start time: ${status.start}
    End time: ${status.end}
    Duration: ${status.end - status.start}
    Successful backed up VM number: ${nSuccess}
    Failed backed up VM: ${nCalls - nSuccess}
    `
  )
}

class BackupReportsXoPlugin {
  constructor (xo) {
    this._xo = xo
  }

  configure (conf) {
    this._conf = conf
  }

  load () {
    this._xo.on('job:terminated', listener)
  }

  unload () {
    this._xo.removeListener('job:terminated', listener)
  }
}

// ===================================================================

export default ({xo}) => new BackupReportsXoPlugin(xo)

@@ -304,16 +304,44 @@
 alls++%0A%0A
+    let vmName%0A%0A    try %7B%0A  
     cons
@@ -381,16 +381,112 @@
 rams.id)
+%0A      vmName = vm.name_label%0A    %7D catch (e) %7B%0A      vmName = 'NoSuchObject, no vm found'%0A    %7D
 %0A%0A    co
@@ -516,27 +516,20 @@
 me: $%7Bvm
-.n
+N
 ame
-_label
 %7D%0A      

Fix NoSuchObject exception