import path from 'path'
import Parent from '../base/serve.mjs'
import fs from 'fs/promises'
import fsSync from 'fs'
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: [
      'imageLink',
      'videoLink',
      'error',
      'siteUrl',
      'siteUrlBase',
      'version',
      'nonce',
      'in_debug',
      'inputVideo',
      'inputImage'
    ] })
  }

  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 = {
      imageLink: ctx.query.get('i') || '',
      videoLink: ctx.query.get('v') || '',
      error: ctx.state.error || '',
      inputVideo: ctx.state.video || ctx.query.get('v') || '',
      inputImage: ctx.state.image || ctx.query.get('i') || '',
      siteUrl: this.frontend + ctx.url,
      siteUrlBase: this.frontend + '/',
      version: this.version,
      nonce: ctx.state.nonce,
      in_debug: config.get('NODE_ENV') === 'development' && false,
    }

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