import Express from 'express'
import Morgan from 'morgan'
import { Server as HttpServer } from 'http'
import SocketIO from 'socket.io'
import { readSettings } from './settings'
import { printHandler } from './print'

const expressApp = Express()

expressApp.use(Morgan('combined'))

const httpServer = HttpServer(expressApp)
const io = SocketIO(httpServer, {
    path: '/printers-tray'
})

/**
 * 
 */
export const createServer = async () => {
    io.on('connection', socket => printHandler(socket))
    
    const { server } = readSettings()
    return await httpServer.listen(server.port, server.host)
}

/**
 * 
 */
export const restartServer = async () => {
    await httpServer.close()
    return await createServer()
}
