const _ = require('lodash/fp')
const { saveConfig, loadLatest } = require('../lib/new-settings-loader')
const { cassetteMaxCapacity } = require('../lib/constants')

exports.up = function (next) {
  return loadLatest()
    .then(({ config }) => {
      const fiatBalance1 = config.notifications_fiatBalanceCassette1
      const fiatBalance2 = config.notifications_fiatBalanceCassette2
      const overrides = config.notifications_fiatBalanceOverrides
      const newConfig = {}
      if (fiatBalance1) {
        newConfig.notifications_fillingPercentageCassette1 = (100 * (fiatBalance1 / cassetteMaxCapacity)).toFixed(0)
        newConfig.notifications_fiatBalanceCassette1 = null
      }
      if (fiatBalance2) {
        newConfig.notifications_fillingPercentageCassette2 = (100 * (fiatBalance2 / cassetteMaxCapacity)).toFixed(0)
        newConfig.notifications_fiatBalanceCassette2 = null
      }

      if (overrides) {
        newConfig.notifications_fiatBalanceOverrides = _.map(override => {
          if (override.fiatBalanceCassette1) {
            override.fiatBalanceCassette1 = (100 * (override.fiatBalanceCassette1 / cassetteMaxCapacity)).toFixed(0)
          }
          if (override.fiatBalanceCassette2) {
            override.fiatBalanceCassette2 = (100 * (override.fiatBalanceCassette2 / cassetteMaxCapacity)).toFixed(0)
          }
          const {
            fiatBalanceCassette1: fillingPercentageCassette1,
            fiatBalanceCassette2: fillingPercentageCassette2,
            ...rest } = override
          return { fillingPercentageCassette1, fillingPercentageCassette2, ...rest }
        }, config.notifications_fiatBalanceOverrides)
      }
      return saveConfig(newConfig)
        .then(() => next())
    })
    .catch(err => {
      if (err.message === 'lamassu-server is not configured') {
        return next()
      }
      console.log(err.message)
      return next(err)
    })
}

module.exports.down = function (next) {
  next()
}

@@ -987,24 +987,57 @@
 erride =%3E %7B%0A
+          const newOverride = %7B%7D%0A
           if
@@ -1075,33 +1075,36 @@
 ) %7B%0A            
-o
+newO
 verride.fiatBala
@@ -1093,32 +1093,38 @@
 wOverride.fi
-atBalanc
+llingPercentag
 eCassette1 =
@@ -1268,17 +1268,20 @@
         
-o
+newO
 verride.
@@ -1278,32 +1278,38 @@
 wOverride.fi
-atBalanc
+llingPercentag
 eCassette2 =
@@ -1408,161 +1408,71 @@
     
-const %7B%0A            fiatBalanceCassette1: fillingPercentageCassette1,%0A            fiatBalanceCassette2: fillingPercentageCassette2,%0A            ...rest %7D
+newOverride.machine = override.machine%0A          newOverride.id
  = o
@@ -1478,16 +1478,20 @@
 override
+.id%0A
 %0A       
@@ -1504,75 +1504,19 @@
 urn 
-%7B fillingPercentageCassette1, fillingPercentageCassette2, ...rest %7D
+newOverride
 %0A   

simplify object construction