
import express from 'express'
import path from 'path'
import fs from 'fs'
import favicon from 'serve-favicon'
import bodyParser from 'body-parser'
import ejs from 'ejs'
import pjson from '../../package.json'
import config from '../../config.json'
import * as api from './api.js'
import routes from './routes.js'

global._config = config
global._rootDir = `${__dirname}/..`
global._staticPath = `${global._rootDir}/static`


// Server
var app = express()

//Set up ejs to parse .html
app.engine( 'html', ejs.renderFile )

// view engine setup
app.set( 'views', global._staticPath)
app.set( 'view engine', 'html' )

// public access folders
app.use( express.static( global._staticPath))

// add favicon
if(fs.existsSync(`${global._staticPath}/images/favicon.ico`)) {
  app.use( favicon(`${global._staticPath}/images/favicon.ico`))
}

app.use( bodyParser.json() )
app.use( bodyParser.urlencoded({ extended: true }) )

if(config.prerenderServer) {
  app.use(require('prerender-node').set('prerenderServiceUrl', config.prerenderServer))
}

//API
if(config.api) {
  app.use(api.config)
  app.use('/api', api.proxy)
}

// Routes
app.use('/', routes)

var port = config.port || process.env.PORT || 3000

var server = app.listen(port, () => {
  console.log('Express server listening on port ' + server.address().port)
})
