const reactanceCalculator = require('../../../tools/reactance/index.js')

const handlers = {
  setReactanceState(changedData) {
    this.setData(reactanceCalculator.updateState(this.data, changedData))
  },

  toggleReactanceMode() {
    this.setReactanceState({
      reactanceModeIndex: this.data.reactanceModeKey === 'inductive' ? 0 : 1
    })
  },

  onReactanceFrequencyInput(event) {
    this.setReactanceState({
      reactanceFrequencyValue: event.detail.value
    })
  },

  onReactanceReactiveInput(event) {
    this.setReactanceState({
      reactanceReactiveValue: event.detail.value
    })
  },

  clearReactanceInputs() {
    this.ignoreReactanceBlurUntil = Date.now() + 300
    this.setData(reactanceCalculator.clearInputs(this.data))
  },

  onReactanceFrequencyUnitChange(event) {
    this.setReactanceState({
      reactanceFrequencyUnitIndex: Number(event.detail.value)
    })
  },

  onReactanceReactiveUnitChange(event) {
    const unitIndex = Number(event.detail.value)
    const field = this.data.reactanceModeKey === 'inductive'
      ? 'reactanceInductanceUnitIndex'
      : 'reactanceCapacitanceUnitIndex'

    this.setReactanceState({
      [field]: unitIndex
    })
  },

  onReactanceValueBlur(event) {
    if (this.ignoreReactanceBlurUntil && Date.now() < this.ignoreReactanceBlurUntil) return

    const field = event.currentTarget.dataset.field

    this.setData(reactanceCalculator.normalizeValue(this.data, field, event.detail.value))
  }
}

module.exports = {
  handlers
}
