const filterCalculator = require('../../../tools/filter/index.js')

const handlers = {
  setFilterState(changedData) {
    this.setData(filterCalculator.updateState(this.data, changedData))
  },

  toggleFilterNetwork() {
    this.setFilterState({
      filterNetworkIndex: this.data.filterNetworkKey === 'rl' ? 0 : 1
    })
  },

  toggleFilterResponse() {
    this.setFilterState({
      filterResponseIndex: this.data.filterResponseKey === 'highpass' ? 0 : 1
    })
  },

  onFilterNetworkChange(event) {
    this.setFilterState({
      filterNetworkIndex: Number(event.detail.value)
    })
  },

  onFilterResponseChange(event) {
    this.setFilterState({
      filterResponseIndex: Number(event.detail.value)
    })
  },

  onFilterResistanceInput(event) {
    this.setFilterState({
      filterResistanceValue: event.detail.value
    })
  },

  onFilterReactiveInput(event) {
    this.setFilterState({
      filterReactiveValue: event.detail.value
    })
  },

  onFilterFrequencyInput(event) {
    this.setFilterState({
      filterFrequencyValue: event.detail.value
    })
  },

  clearFilterInputs() {
    this.ignoreFilterBlurUntil = Date.now() + 300
    this.setFilterState({
      filterFrequencyValue: '',
      filterReactiveValue: '',
      filterResistanceValue: ''
    })
  },

  onFilterResistanceUnitChange(event) {
    this.setFilterState({
      filterResistanceUnitIndex: Number(event.detail.value)
    })
  },

  onFilterReactiveUnitChange(event) {
    const unitIndex = Number(event.detail.value)
    const field = this.data.filterNetworkKey === 'rl'
      ? 'filterInductanceUnitIndex'
      : 'filterCapacitanceUnitIndex'

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

  onFilterFrequencyUnitChange(event) {
    this.setFilterState({
      filterFrequencyUnitIndex: Number(event.detail.value)
    })
  },

  onFilterValueBlur(event) {
    if (this.ignoreFilterBlurUntil && Date.now() < this.ignoreFilterBlurUntil) return

    const field = event.currentTarget.dataset.field
    const valueKeyMap = {
      frequency: 'filterFrequencyValue',
      reactive: 'filterReactiveValue',
      resistance: 'filterResistanceValue'
    }
    const valueKey = valueKeyMap[field]

    if (this.data.filterComputedKey === field && valueKey && !this.data[valueKey]) return

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

module.exports = {
  handlers
}
