import type { ParallelTaskExecuteContext } from '../handler'
import type { PrivateCustomEventName, ReplyWorkerMessage } from '../types'

import { ParallelHandler } from '../handler'
import { createEventBus } from '../utils'

// eslint-disable-next-line ts/ban-ts-comment
// @ts-ignore
import TranscodeWorker from '../worker/transcode-worker?worker&inline'

const $bus = createEventBus<PrivateCustomEventName>()

class ResponseTranscode extends ParallelHandler<string, string> {
  private transcodeWorkerInstance: Worker | null = null

  onActive(): void {
    this.transcodeWorkerInstance = new TranscodeWorker()

    this.transcodeWorkerInstance?.addEventListener('message', (event: MessageEvent<ReplyWorkerMessage<any>>): void => {
      const { type, data } = event.data

      if (type === 'success') {
        const { audioData } = data
        this.forwardToHandler(audioData)
      }
      this.taskCompletedCallback(data.uuid)
    })
  }

  public execute(context: ParallelTaskExecuteContext<string, string>): void {
    if (context.isLastExecute) {
      this.taskCompletedCallback(context.taskItem.uuid)
      return
    }

    this.transcodeWorkerInstance?.postMessage({
      type: 'send',
      data: context.taskItem,
    })
  }

  protected onFinish(): void {
    $bus.emit('_responseTranscodeFinish')
    if (this.transcodeWorkerInstance) {
      this.transcodeWorkerInstance.terminate()
    }
  }
}

export default ResponseTranscode
