const fs = require('fs')
const Handlebars = require('handlebars')
const OutputItem = require('./OutputItem')

class Output {
  constructor () {
    this.items = []
    this.timestamp = null
  }

  addItem (...p) {
    this.items.push(new OutputItem(...p))
  }

  async compileTemplate () {
    const templateFile = await fs.readFileSync('./output/template.hbs', 'utf8')
    const template = Handlebars.compile(templateFile)
    return template(this)
  }

  async writeToFile (content) {
    const filename = './public/index.html'

    try {
      await fs.unlinkSync(filename)
    } catch {
      console.log('File probably doesnt exist')
    }
    fs.writeFileSync(filename, content, 'utf-8')
  }

  async submit () {
    this.timestamp = new Date()
    const content = await this.compileTemplate()
    await this.writeToFile(content)
  }
}

module.exports = new Output()
