// http
const http = require('http')
// filesystem
const fs = require('fs')
// server config
var config = require('./config.json');
// node date time
var node_time = require('node-datetime')

// 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')


// mongodb connect function
async function connect_mongodb(MongoClient)
{
    const mongodb_client = new MongoClient(config.mongodb_url)
    try 
    {
        // connect to the MongoDB cluster (now just database)
        await mongodb_client.connect()

        // connect to database
        const database = mongodb_client.db(config.database_name)
        console.log('Database connection status:', await database.command({ping: 1}))

        // get titles collection
        var title = database.collection("title")
        console.log(`Titles count: ${await title.countDocuments()}`)
        title.insertOne({title:{en:"Title", ru:"Название"}, 
            location:{en:"Russia, Moscow", ru:"Россия, Москва"}, 
            description:{en:"Best RC ...", ru:"Лучший ЖК ..."},
            image:{main:"URL1", second:"URL2"}
        })
    }
    catch(e)
    {
        console.error(e)
    }
    // finally
    // {
    //     await mongodb_client.close()
    //     console.log("Database connection closed")
    // }
}

// response function
function create_response(request)
{
    var request_json = JSON.parse(request)
    switch(request_json.verb)
    {
        case 'GET_TITLES':
            break;
        case 'PLAN_SESSION':
            break;
        case 'CREATE_SESSION':
            break;
        case 'CONNECT_SESSION':
            break;
        case 'CONNECT_SESSION_WITH_CODE':
            break;
        default:
    }
    return '{"verb":"WAIT"}'
}




// connect to mongodb
const {MongoClient} = require('mongodb')
connect_mongodb(MongoClient).catch(console.error)

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

        request.on('end', function()
        {
            response.writeHead(200, {'Content-Type': 'message'})
            response.end(create_response(body))
            console.log(body)
        })
    }
    else
    {
        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}`)