var cproc = require('child_process');
var execSync = cproc.execSync;
const exec = cproc.exec;
const spawn = cproc.spawn;
var net = require('http');

var os = require('os');
var ifaces = os.networkInterfaces();
let ip = "0.0.0.0";
let pwd = process.cwd();

var portrange = 45000;
var maxportrange = 47000;
async function getPort(exc) {
    var port = portrange;
    portrange += 1;
    if (portrange >= maxportrange) {
        portrange = 45000;
    }
    // var server = net.createServer();
    if (exc && port == exc) {
        port = port + 1;
    }
    // console.log(port)
    // await server.listen(port, function (err) {
    //     server.close()
    // })
    // server.on('error', function (err) {
    //     getPort()
    // })

    return port
}

function getIp() {
    Object.keys(ifaces).forEach(function (ifname) {
        var alias = 0;

        ifaces[ifname].forEach(function (iface) {
            if ('IPv4' !== iface.family || iface.internal !== false) {
                // skip over internal (i.e. 127.0.0.1) and non-ipv4 addresses
                return;
            }
            if (alias >= 1) {
                // this single interface has multiple ipv4 addresses
                // console.log(ifname + ':' + alias, iface.address);
            } else {
                // this interface has only one ipv4 adress
                console.log(ifname,iface.address)
                if (ifname == "eth0" || ifname == "en0") {
                    ip = iface.address;
                }
                // console.log(ifname, iface.address);
            }
            ++alias;
        });
    });
}
getIp();

const redis = require('redis');
const bluebird = require("bluebird");
const client = redis.createClient('6379', '127.0.0.1');

exports.initial = async function () {
    await this.bindDefault();
    let _this = this;
    //初始化一个docker镜像
    let xterm_port,mock_port;
    let res_str = await client.getAsync(`${this.request.ip}docker`).then(function (records) {
        return records
    });
    if(res_str == null){
         xterm_port = await getPort();
         mock_port = await getPort(xterm_port);
    }else{
        let res = JSON.parse(res_str);
        xterm_port = res.xterm_port;
        mock_port = res.mock_port;
    }

    let run_command = `docker run --privileged -d  -v ${pwd}/uploads:/root/BlackPearl/uploads -e "BP_ENV=debug" -p ${xterm_port}:3000 -p ${mock_port}:10085 192.168.4.36/playground/debug_image /sbin/init`;
    var re_str = execSync(run_command);
    console.log(run_command);
    var id = String(re_str).replace(/\n/, "");
    let mock_url = `http://${ip}:${mock_port}`;
    let term_url = `http://${ip}:${xterm_port}` ;
    client.set(`${_this.request.ip}docker`, JSON.stringify({
        id: id,
        is_debug: true,
        mock_port: mock_port,
        xterm_port: xterm_port
    }));
    spawn("sh", ["./shell_script/start_docker_image.sh", id]);
    this.response.body = { term_url: term_url, mock_url: mock_url}
    return
}
exports.initial.__method__ = "ALL";

exports.have_image = async function () {
    await this.bindDefault();
    // 判断是否有活跃的镜像，如果有则提示已经存在，可能要关闭之前的
    let res_str =  await client.getAsync(`${this.request.ip}docker`).then(function(records){
        return records;
    });
    console.log(res_str)
    if(res_str != null){
        this.response.body =  JSON.parse(res_str);
    }else{
        this.response.body = { is_debug : false}
    }
    return 
}
exports.have_image.__method__ = 'ALL';

exports.run = async function () {
    await this.bindDefault();
    // 启动一个docker镜像
    // 
    /*
    一个IP只能启动一个镜像，再申请的时候，如果已经存在活跃的镜像，就要关闭之前的镜像，重新启动一个
    return {id:返回的是这个镜像的ID,port:本地demo服务端口1,port2:本地xterm的端口号}
    */
    return
}
exports.run.__method__ = 'ALL';

exports.stop = async function () {
    //关闭并退出docker镜像
    let res_str = await client.getAsync(`${this.request.ip}docker`).then(function (records) {
        return records
    });
    // console.log(res_str)
    if (res_str != null) {
        let res = JSON.parse(res_str);
        spawn("sh", ["./shell_script/stop_docker_image.sh", res.id]);

        client.set(`${this.request.ip}docker`, JSON.stringify({
            id: "",
            is_debug: false,
            mock_port: res.mock_port,
            xterm_port: res.xterm_port
        }));


        // client.del(`${this.request.ip}docker`);
        this.response.body = { code: "0000" }
    } else {
        this.response.body = { code: "0001" }
    }

    return
}
exports.stop.__method__ = 'GET';
