import IatRecorder from '@/util/iat-recorder'
import { onBeforeUnmount, ref } from 'vue'

type Status = 'init' | 'ing' | 'stop' | 'end'
export default function useVoiceRecorder() {
  const iatRecorder: any = new IatRecorder()
  const result = ref('')
  const status = ref<Status>('init')

  iatRecorder.onTextChange = function (txt: string) {
    result.value = txt
  }
  iatRecorder.onWillStatusChange = function (_, curStatus: Status) {
    status.value = curStatus
  }
  onBeforeUnmount(() => {
    resetRecorder()
  })

  function toggleRecorder() {
    if (iatRecorder.status === 'ing') {
      iatRecorder.stop()
    } else {
      iatRecorder.start()
    }
  }

  function resetRecorder() {
    iatRecorder.stop()
    iatRecorder.status === 'init'
    status.value = 'init'
    result.value = ''
  }

  return { result, toggleRecorder, status, resetRecorder }
}
