const express = require('express')
const webserver = express()
const port = 3003
const serveIndex = require('./src/utils/serve_index')
const {engine} = require('express-handlebars')
const indexRouter = require('./src/router/indexRouter')
const { handlebars } = require('hbs')
const bodyParser = require('body-parser')

const publicPath = "/public"
const inUrlPath = "public"

webserver.engine('.hbs', engine({extname: '.hbs', helpers: {
  ifDivisibleBy: function (index, divisor, options) {
    if ((index+1) % divisor === 0) {
      return options.fn(this);
    }
  },
  ifEquals: function(arg1, arg2, options) {
    return (arg1 == arg2) ? options.fn(this) : options.inverse(this);
  },
  raw: function(string){
    return (new handlebars.SafeString(string))
  }
}}));
webserver.set('view engine', '.hbs');

webserver.use(publicPath, express.static(inUrlPath), serveIndex(inUrlPath, {
}))

webserver.use(bodyParser.urlencoded({extend: false}));

webserver.use(bodyParser.json());


webserver.listen(port, () => {
  console.log(`Listening on port ${port}`)
})

webserver.use('/', indexRouter)

webserver.use((err, _req, res, next) =>{
  if (err){
    console.error(err)
    res.send("It was terrible. Check the logs for more details.")
  } 
  else next()
})

webserver.use((_req, res, _next) => {
  res.status(404).render('404', {
    stylesheet: '/public/styles/404/index.css',
    title: "404!"
  });
});