import { Router, Request, Response } from 'express'
import { Lorem } from '@pawel-up/data-mock/Lorem.js'
import { Types } from '@pawel-up/data-mock/Types.js'
import { BaseApi } from './BaseApi.js'
import cors from 'cors'

const router = Router()
export default router

class StreamRoute extends BaseApi {
  #lorem = new Lorem()
  #types = new Types()

  async index(req: Request, res: Response): Promise<void> {
    res.writeHead(200, {
      'Content-Type': 'text/plain; charset=UTF-8',
      'Transfer-Encoding': 'chunked',
    })
    this.#writeChunk(res)
    let time = 0
    for (let i = 0; i < 4; i++) {
      const timeout = this.#types.number({ min: 1, max: 10 })
      time += timeout
      setTimeout(() => this.#writeChunk(res), timeout)
    }
    time += 5
    setTimeout(() => {
      res.end('END')
    }, time)
  }

  async chunked(req: Request, res: Response): Promise<void> {
    res.writeHead(200, {
      'Content-Type': 'text/plain; charset=UTF-8',
      'Transfer-Encoding': 'chunked',
    })
    this.#writeChunk(res)
    let time = 0
    for (let i = 0; i < 4; i++) {
      const timeout = this.#types.number({ min: 1, max: 10 })
      time += timeout
      setTimeout(() => this.#writeChunk(res), timeout)
    }
    time += 5
    setTimeout(() => {
      res.end('END')
    }, time)
  }

  #writeChunk(res: Response): void {
    const word = this.#lorem.word({ length: 128 })
    res.write(`${word}\n`)
  }
}

const api = new StreamRoute()
api.setCors(router)
const checkCorsFn = api._processCors
router.get('/', cors(checkCorsFn), api.index.bind(api))
router.get('/chunked', cors(checkCorsFn), api.chunked.bind(api))
