const crcTool = require('../../../tools/crc-hash/crc-tool.js')
const {
  isCancelError,
  loadSelectedFile
} = require('../../../repositories/file.js')

const handlers = {
  onCrcPresetChange(event) {
    const presetIndex = Number(event.detail.value)

    this.setData({
      ...crcTool.createPresetState(presetIndex),
      ...crcTool.createEmptyResultState()
    })
  },

  onCrcInputTypeChange(event) {
    this.setData({
      crcInputTypeIndex: Number(event.detail.value)
    })
  },

  onCrcConfigInput(event) {
    const field = event.currentTarget.dataset.field
    if (!field) return
    const isCrcConfigField = crcTool.CRC_CONFIG_FIELDS.includes(field)
    const nextData = {
      [field]: event.detail.value
    }

    if (isCrcConfigField) {
      nextData.crcAlgorithmCollapsed = false
      nextData.crcPresetIndex = crcTool.getCustomPresetIndex()
    }

    this.setData(nextData)
  },

  onCrcReflectChange(event) {
    const field = event.currentTarget.dataset.field
    if (!field) return

    this.setData({
      [field]: !!event.detail.value,
      crcAlgorithmCollapsed: false,
      crcPresetIndex: crcTool.getCustomPresetIndex()
    })
  },

  toggleCrcAlgorithmPanel() {
    this.setData({
      crcAlgorithmCollapsed: !this.data.crcAlgorithmCollapsed
    })
  },

  onCrcDataInput(event) {
    this.crcFileBytes = null
    this.setData({
      crcDataText: event.detail.value,
      crcFileName: '',
      crcFileSizeText: ''
    })
  },

  calculateCrc() {
    try {
      this.setData(crcTool.calculateFromState(this.data, this.crcFileBytes))
    } catch (error) {
      const message = error && error.message ? error.message : '计算失败'
      if (this.pageToast) this.pageToast.show(message, 'error')
    }
  },

  async loadCrcFileFromMessage() {
    try {
      const file = await loadSelectedFile('auto')
      this.crcFileBytes = file.bytes
      this.setData({
        crcDataLengthText: file.sizeText,
        crcDataText: '',
        crcFileName: file.name,
        crcFileSizeText: file.sizeText
      })
      this.calculateCrc()
    } catch (error) {
      const message = error && (error.errMsg || error.message)
        ? (error.errMsg || error.message)
        : '读取文件失败'

      if (!isCancelError(error) && this.pageToast) {
        this.pageToast.show(message, 'error')
      }
    }
  },

  clearCrcInput() {
    this.crcFileBytes = null
    this.setData({
      crcDataLengthText: '0 bytes',
      crcDataText: '',
      crcFileName: '',
      crcFileSizeText: '',
      ...crcTool.createEmptyResultState()
    })
  }
}

module.exports = {
  handlers
}
