const {
  BaseKonnector,
  log,
  errors,
  addData,
  hydrateAndFilter,
  cozyClient
} = require('cozy-konnector-libs')
const rp = require('request-promise')
const moment = require('moment')
require('moment-timezone')

moment.locale('fr') // set the language
moment.tz.setDefault('Europe/Paris') // set the timezone

const startDate = moment()
  .subtract(10, 'day')
  .format('MM/DD/YYYY')
const endDate = moment().format('MM/DD/YYYY')

module.exports = new BaseKonnector(start)

// The start function is run by the BaseKonnector instance only when it got all the account
// information (fields). When you run this connector yourself in "standalone" mode or "dev" mode,
// the account information come from ./konnector-dev-config.json file
async function start(fields, cozyParameters) {
  try {
    // resetting data for demo only
    // await resetData()
    const baseUrl = cozyParameters.secret.eglBaseURL
    const apiAuthKey = cozyParameters.secret.eglAPIAuthKey

    log('info', 'Authenticating ...')
    const response = await authenticate(
      fields.login,
      fields.password,
      baseUrl,
      apiAuthKey
    )
    log('info', 'Successfully logged in')
    log('info', 'Getting data')
    const loadProfile = await getData(response, baseUrl, apiAuthKey)
    log('info', 'Saving data to Cozy')
    storeLoadProfile(loadProfile)
  } catch (error) {
    throw new Error(error.message)
  }
}

async function authenticate(login, password, baseUrl, apiAuthKey) {
  const authRequest = {
    method: 'POST',
    uri: baseUrl + '/connect.aspx',
    headers: {
      AuthKey: apiAuthKey,
      'Content-Type': 'application/x-www-form-urlencoded'
    },
    form: {
      login: login,
      pass: password
    },
    json: true
  }
  try {
    const response = await rp(authRequest)
    if (response.codeRetour === 100) {
      return response
    } else {
      throw new Error(errors.LOGIN_FAILED)
    }
  } catch (error) {
    throw error
  }
}

async function getData(response, baseUrl, apiAuthKey) {
  const dataRequest = {
    method: 'POST',
    uri: baseUrl + '/getAllAgregatsByAbonnement.aspx',
    headers: {
      AuthKey: apiAuthKey,
      'Content-Type': 'application/x-www-form-urlencoded'
    },
    form: {
      token: response.resultatRetour.token,
      num_abt: response.resultatRetour.num_abt,
      date_debut: startDate,
      date_fin: endDate
    },
    json: true
  }
  try {
    const response = await rp(dataRequest)
    switch (response.codeRetour) {
      case 100:
        return format(response)
      case -2:
        throw new Error(errors.LOGIN_FAILED)
      case -1:
        throw new Error(errors.VENDOR_DOWN)
      default:
        throw new Error(errors.UNKNOWN_ERROR)
    }
  } catch (error) {
    throw new Error(errors.VENDOR_DOWN)
  }
}

function format(response) {
  const data = response.resultatRetour.slice(1).map((value, index) => {
    return {
      time: moment(value.DateReleve, moment.ISO_8601).format('YYYY-MM-DD'),
      load: value.ValeurIndex - response.resultatRetour[index].ValeurIndex,
      type: value.TypeAgregat
    }
  })
  return data
}

function storeLoadProfile(loadProfile) {
  return hydrateAndFilter(loadProfile, 'egl.loadprofile', {
    keys: ['time']
  }).then(filteredDocuments => {
    addData(filteredDocuments, 'egl.loadprofile')
  })
}

// eslint-disable-next-line no-unused-vars
async function resetData() {
  const result = await cozyClient.data.findAll('egl.loadprofile')
  if (result.error) {
    // eslint-disable-next-line no-console
    console.error('Error while fetching loads')
  }
  for (const load of result) {
    await cozyClient.data.delete('egl.loadprofile', load)
  }
}