import { Flaska, QueryHandler, JsonHandler } from 'flaska'
import config from './config.mjs'
import StaticRoutes from './static_routes.mjs'
import Proxy from './proxy.mjs'

export default class Server {
  constructor(http, port, core, opts = {}) {
    Object.assign(this, opts)
    this.http = http
    this.port = port
    this.core = core

    this.flaskaOptions = {
      appendHeaders: {
        'Content-Security-Policy': `default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src * data: blob:; font-src 'self' data:; object-src 'none'; frame-ancestors 'none'`,
      },
      log: this.core.log,
      nonce: ['script-src'],
      nonceCacheLength: 50,
    }

    this.init()
  }

  init() { }

  runCreateServer() {
    // Create our server
    this.flaska = new Flaska(this.flaskaOptions, this.http)

    // configure our server
    console.log(config.get('NODE_ENV'))
    if (config.get('NODE_ENV') === 'development') {
      this.flaska.devMode()
    }

    this.flaska.onerror(err => {
      console.log(err)
      ctx.log.error(err)
      ctx.status = 500
    })

    this.flaska.before(function(ctx) {
      ctx.state.started = new Date().getTime()
      ctx.req.ip = ctx.req.headers['x-forwarded-for'] || ctx.req.connection.remoteAddress
      ctx.log = ctx.log.child({
        id: Math.random().toString(36).substring(2, 14),
      })
    })
    
    let healthChecks = 0
    let healthCollectLimit = 60 * 60 * 12

    this.flaska.after(function(ctx) {
      if (ctx.aborted && ctx.status === 200) {
        ctx.status = 299
      }
      let ended = new Date().getTime()
      var requestTime = ended - ctx.state.started

      let status = ''
      let level = 'info'
      if (ctx.status >= 400) {
        status = ctx.status + ' '
        level = 'warn'
      }
      if (ctx.status >= 500) {
        level = 'error'
      }

      if (ctx.url === '/health' || ctx.url === '/api/health') {
        healthChecks++
        if (healthChecks >= healthCollectLimit) {
          ctx.log[level]({
            duration: Math.round(ended),
            status: ctx.status,
          }, `<-- ${status}${ctx.method} ${ctx.url} {has happened ${healthChecks} times}`)
          healthChecks = 0
        }
        return
      }

      ctx.log[level]({
        duration: requestTime,
        status: ctx.status,
        ip: ctx.req.ip,
      }, (ctx.aborted ? '[ABORT]' : '<--') + ` ${status}${ctx.method} ${ctx.url}`)
    })
  }

  registerRoutes() {
    var stat = new StaticRoutes()
    var proxy = new Proxy()
    stat.register(this)
    proxy.register(this)
  }

  runStartListen() {
    return this.flaska.listenAsync(this.port).then(() => {
      this.core.log.info('Server is listening on port ' + this.port)
    })
  }

  run() {
    this.runCreateServer()
    this.registerRoutes()
    return this.runStartListen()
  }
}
