// session server
// http
const http = require('http')
// filesystem
const fs = require('fs')
// server config
const config = require('./config.json');
// node date time
const node_time = require('node-datetime')
// titles for process creation
const titles = require('./titles.json')

const { spawn } = require('node:child_process')

// write startup server history
var logs_dir = './logs'
if (!fs.existsSync(logs_dir))
    fs.mkdirSync(logs_dir)

fs.appendFileSync(`./${logs_dir}/launch_history.log`, (node_time.create().format('Y-m-d H:M:S')).toString() + '\n')

// response function
async function create_response(request, callback) {
    var response = ''
    try {
        switch(request.verb) {
            case 'CREATE_SESSION':
                var title_info
                titles.forEach((title) => {
                    if (title.title == request.title) {
                        title_info = title
                    }
                })
                if (title_info == null) {
                    response = '{"msg":"TITLE_NOT_EXISTS"}'
                    break
                }

                const process = spawn(title_info.path, ['', ''])

                process.on('close', (code) => {
                    console.log(`child process exited with code ${code}`);
                })

                response = `{"msg":"SESSION_CREATED", "link":"http://${title_info.title}"}`
                break
            case 'CONNECT_SESSION':
                break
            default:
                response = '{"msg":"UNKNOWN_VERB"}'
        }
        callback(response)
    }
    catch(e) {
        console.error(e)
    }
}


// start http server
const server = http.createServer(function(request, response) {
    if (request.method == 'POST') {
        var body = ''
        
        request.on('data', function(data) {
            body += data
        })

        request.on('end', function() {
            response.writeHead(200, {'Content-Type': 'message'})
            try {
                create_response(JSON.parse(body), function(message) {
                    response.end(message)
                })
            }
            catch(e) {
                console.error(e)
            }
            console.log('received: "', body, '"')
        })
    }
    else {
        var message = 'UNDEFINED_REQUEST' + ': ' + request.method.toString()
        response.writeHead(200, {'Content-Type': 'message'})
        response.end(message)
        console.log(message)
    }
})

server.listen(config.port, config.ip)
console.log(`Listening at http://${config.ip}:${config.port}`)