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


// // filesystem
// const fs = require('fs')

// // node date time
// const node_time = require('node-datetime')
// // titles for process creation
// const titles = require('./titles.json')

const port_alloc = require('../../lib/port_alloc.js')
const titles = require('../titles.json')
const configg = require('../config.json')
const { spawn } = require('node:child_process')
const child_process = require('child_process')
const http_client = require('../../lib/http_client.js')

const app_port_begin = configg.session_ports.app_begin
const http_port_begin = configg.session_ports.http_begin
const ports_count = configg.session_ports.count

const app_args_static = configg.app_args_static
const app_args_ip = configg.app_args_runtime.ip
const server_ip = configg.ip
const app_args_port = configg.app_args_runtime.port

const webrtc_cirrus_path = configg.webrtc_args_static.cirrus_path

const coordinator_port = configg.coordinator.port
const coordinator_ip = configg.coordinator.ip

// const http_client = require('../lib/http_client.js')

// SHALL FIX IT IN FUTURE BECAUSE IT IS NOT THE REST API
var app_port_alloc = new port_alloc(app_port_begin, ports_count)
var http_port_alloc = new port_alloc(http_port_begin, ports_count)

module.exports.create_session = async (req, res, next) => {
    //create?title=name&next_var=0
    try {
        var app_info
        titles.forEach((title) => {
            if (title.title == req.query.title) {
                app_info = title
            }
        })
        if (!app_info)
            throw new Error('app info not exists')

        var app_port
        var http_port
        try {
            app_port = app_port_alloc.get()
            http_port = http_port_alloc.get()
        } catch(e) {
            throw new Error(e)
        }
        
        // start app_proc
        const app_proc = spawn(app_info.path, [].concat(app_args_static, 
            [app_args_ip + server_ip, app_args_port + app_port.toString()]), {
                detached: true
            })
        app_proc.on('error', function(err) {
            logger_runtime.error(err)
            response = {msg:'APP_PROC_ERROR'}
            callback(response)
            return
        })
        app_proc.on('close', (code) => {
            app_port_alloc.free(app_port)
        })

        // start webrtc server
        const webrtc_proc = child_process.fork(webrtc_cirrus_path, [http_port.toString(), app_port.toString()], {
                detached: true
            })
        webrtc_proc.on('error', function(err) {
            logger_runtime.error(err)
            response = {msg:'WEBRTC_PROC_ERROR'}
            callback(response)
            return
        })
        webrtc_proc.on('close', (code) => {
            http_port_alloc.free(http_port)
            // if webrtc server closed, kill app proc and send session end message to server
            if (process.platform === 'win32') {
                spawn('taskkill', ['/pid', app_proc.pid, '/f', '/t'])
            }
            else {
                app_proc.kill('SIGINT')
            }
            http_client.get({
                host: coordinator_ip,
                port: coordinator_port,
                path: `/session/close?session_id=${req.query.session_id}`
            }, async function(answer) {
            }, function(err) {
                next(Error('session server not working'))
            })
            // new http_client(coordinator_ip, coordinator_port).post(
            //     JSON.stringify({verb:'CLOSE_SESSION', session_id:req.query.session_id}), function(answer) {
                    
            //     },
            //     function(error) {

            //     })
            
        })
        res.json({msg:'SESSION_CREATED', link:`http://${server_ip+':'+http_port}`})
        // callback(response)
        // return

        // get request
        // 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) {

        //     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) => {
}