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

export default class ServeHandler extends Parent {
  loadTemplate(indexFile) {
    this.template = dot.template(indexFile.toString(), { argName: ['headerDescription', 'headerImage', 'headerTitle', 'headerUrl', 'payloadData', 'payloadTree', 'version', 'nonce', 'type', 'banner', 'media', 'in_debug'] })
  }

  async serveIndex(ctx) {
    if (config.get('NODE_ENV') === 'development') {
      let indexFile = await fs.readFile(path.join(this.root, 'index.html'))
      this.loadTemplate(indexFile)
    }

    let payload = {
      in_debug: config.get('NODE_ENV') === 'development' && false,
      nonce: ctx.state.nonce,
      headerUrl: '/',
      headerTitle: 'Eignavakt',
    }

    ctx.body = this.template(payload)
    ctx.type = 'text/html; charset=utf-8'
  }
}