import type { SerialTaskExecuteContext } from '../handler'

import TextStreamSlicer from '@minto-ai/text-stream-slicer'
import { SerialHandler } from '../handler'

class TextSplit extends SerialHandler<string, string> {
  private textStreamSlicer = new TextStreamSlicer()

  public execute(
    context: SerialTaskExecuteContext<string, string>,
  ): void {
    if (context.isLastExecute) {
      this.textStreamSlicer.processText('', true).forEach((paragraph) => {
        this.forwardToHandler(paragraph)
      })
    }
    else {
      this.textStreamSlicer.processText(context.taskItem.original!).forEach((paragraph) => {
        this.forwardToHandler(paragraph)
      })
    }
    this.taskCompletedCallback()
  }

  protected onFinish(): void {
    this.executeController?.$bus.emit('_textSplitFinish')
  }
}

export default TextSplit
