import fs from 'fs/promises'
import dot from 'dot'
import Parent from '../base/serve.mjs'
import path from 'path'

export default class ServeHandler extends Parent {
  loadTemplate(indexFile) {
    this.template = dot.template(indexFile.toString(), { argName: [
      'siteUrl',
    ] })
  }

  async serveIndex(ctx) {
    if (process.env.NODE_ENV !== 'production') {
      let indexFile = await fs.readFile(path.join(this.root, 'index.html'))
      this.loadTemplate(indexFile)
    }

    ctx.body = this.template({
      siteUrl: this.frontend + ctx.url,
    })
    ctx.type = 'text/html; charset=utf-8'
  }
}