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

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

    this.setData({
      ...crcTool.createPresetState(presetIndex),
      crcErrorText: ''
    })
  },

  onCrcInputTypeChange(event) {
    this.setData({
      crcErrorText: '',
      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,
      crcErrorText: ''
    }

    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,
      crcErrorText: '',
      crcPresetIndex: crcTool.getCustomPresetIndex()
    })
  },

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

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

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

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

      if (!/cancel/i.test(message) && this.pageToast) {
        this.pageToast.show(message, 'error')
      }
    }
  },

  clearCrcInput() {
    this.crcFileBytes = null
    this.setData({
      crcDataLengthText: '0 bytes',
      crcDataText: '',
      crcErrorText: '',
      crcFileName: '',
      crcFileSizeText: '',
      crcResultBase64: '--',
      crcResultBin: '--',
      crcResultBinLines: [
        {
          id: 'bin-line-0',
          text: '--'
        }
      ],
      crcResultHex: '--'
    })
  }
}

module.exports = {
  handlers
}
