const pkg = require('./package.json')

const path = require('path')
const fs = require('fs')

const yaml = require('node-yaml')
const ip = require('ip')
const express = require('express')
const {createBroadcaster} = require('ec-registry-broadcast')

const app = express()

app.set('view engine', 'ejs')
app.set('views', path.join(__dirname, 'views'))

app.use(require('cookie-parser')())

app.use(require('ec-express-flash-messages'))

app.get('/hello', async function (req, res) {
  res.render('home')
})

app.get('/users/:name/hello', async function (req, res) {
  res.render('home', {name: req.params.name})
})

app.get('/health', async function (req, res) {
  res.contentType('text/text').status(200).send({
    status: 'success',
    statusText: 'Healthy'
  })
})

// return app if being included from another file as middlewarem
if (require.main !== module) {
  return module.exports = app
}

function setupBroadcaster (port) {
  // Setup a broadcaster for service discovery
  createBroadcaster(async function () {
    let manifest = await yaml.read(path.join(__dirname, 'manifest.yml'))
    manifest.server = {
      tags: {
        type: 'http_server'
      },
      protocol: 'http',
      url: `http://${ip.address()}:${port}`,
      host: ip.address(),
      port
    }
    return manifest
  })
}

const port = process.env.WEB_PORT || 0
const server = app.listen(port, function () {
  setupBroadcaster(server.address().port)

  console.log(`${pkg.name} listening on port ${server.address().port}!`)
})
