const db_connection = require('../database/connection.js')

// two bad headers
const http_client = require('../../lib/http_client.js')
const crypto = require('crypto')

module.exports.plan_session = async (req, res, next) => {
    //var session_sheduled = database.collection('session_sheduled')
    //var sessions = await session_sheduled.find().toArray()
    //callback(response)
}

module.exports.create_session = async (req, res, next) => {
    //create?title=name&next_var=0
    try {
        const db = await db_connection.get_db()
        var servers = await db.collection('session_server').find({'title':req.query.title}).toArray()
        if (!servers.length)
            throw new Error('servers not found')

        // find free server and create session
        var session_active = db.collection('session_active')
        var free_server
        var servers_length = servers.length
        for (var i = 0; i < servers_length; ++i) {
            var sessions = await session_active.find({'server_id':servers[i].server_id}).toArray()
            if (servers[i].limit > sessions.length) {
                free_server = servers[i]
                break
            }
        }
        if (!free_server)
            throw new Error('session limit reached')
        
        var session_id = crypto.randomBytes(16).toString('hex')
    
        // create session on session server
        http_client.get({
            host: free_server.ip,
            port: free_server.port,
            path: `/session/create?title=${req.query.title}&session_id=${session_id}`
        }, async function(answer) {
            answer = JSON.parse(answer)
            //console.log(answer.method)
            if (!answer.link) {
                next(Error('session not created'))
                return
            }
            // generate random code for session access
            var code = Math.floor(1000 + Math.random() * 9000)
            while ((await session_active.find({'code':code}).toArray()).length) {
                code = Math.floor(1000 + Math.random() * 9000)
            }
    
            // add session to database
            await session_active.insertOne({
                server_id:free_server.server_id,
                session_id:session_id,
                connection_link:answer.link,
                connection_code:code
            })
            res.json({msg:'SESSION_CREATED', link:answer.link})
        }, function(err) {
            next(Error('session server not working'))
        })
    } catch (e) {
        next(e)
    }
}

module.exports.connect_session = async (req, res, next) => {
    
}

module.exports.close_session = async (req, res, next) => {
    const db = await db_connection.get_db()
    await db.collection('session_active').deleteOne({session_id:req.query.session_id})
    res.json({msg:"SESSION_CLOSED", session_id:req.session_id})
}