var comps = [];
var matrix = [];

function resetComps() {
    comps = [];
}

function resetMatrix() {
    matrix = [];
    for (var i = 0; i < 100; i++) {
        var mxitem = [];
        for (var j = 0; j < 100; j++) {
            mxitem.push(0);
        }
        matrix.push(mxitem);
    }
}

function createCompsCircle(centerX, centerY, radius, units, startAngle) {
    var unitsPlaced = 0;
    for (var angle = startAngle; angle < 360 + startAngle; angle++) {
        var rad = angle * (Math.PI / 180);
        var xrad = radius * Math.cos(rad);
        var yrad = radius * Math.sin(rad);
        var x = 0;
        var y = 0;
        x = Math.round(centerX + xrad);
        y = Math.round(centerY + yrad);
        if (x < 0 || x >= 20) { continue; }
        if (unitsPlaced >= units * 2) { break; }
        if (matrix[x][y]) { continue; }
        var xNeighbour = matrix[x + 1][y] || matrix[x - 1][y];
        var yNeighbour = matrix[x][y + 1] || matrix[x][y - 1];
        if (xNeighbour && yNeighbour) { continue; }
        matrix[x][y] = 1;
        unitsPlaced++;
        if (unitsPlaced % 2) {
            comps.push(addComputer(x, y));
        }
    }
}

function closestTwo(n) {
    if (n < 1) { return 1 }
    var power = 1;
    while (power < n) { power *= 2; }
    return power;
}

function joinComps(comps, hub, istart, id, gateway) {
    hub.setSocketsCount(closestTwo(comps.length));

    for (var i = 0; i < comps.length; i++) {
        addConnection(comps[i], hub, "eth0", "LAN" + (i + 1));
        comps[i].setIp("eth0", "192.168."+id+"." + (istart+i));
        comps[i].setMask("eth0", "255.255.255.0");
        /* comps[i].setGateway(gateway); */
        comps[i].setGateway(gateway);
    }
}
var hub1 = addSwitch(5, 7);
var hub2 = addSwitch(15, 7);
var router = addRouter(10, 3);

addConnection(router, hub1, "LAN1", "LAN"+closestTwo(comps.length));
addConnection(router, hub2, "LAN2", "LAN"+closestTwo(comps.length));

router.setIp("LAN1", "192.168.1.123");
router.setIp("LAN2", "192.168.2.123");
router.setMask("LAN1", "255.255.255.255");
router.setMask("LAN2", "255.255.255.255");

resetComps();
resetMatrix();
createCompsCircle(5, 7, 4, 13, 0, "192.168.1.123");
joinComps(comps, hub1, 0, 1, "192.168.1.123");

resetComps();
resetMatrix();
createCompsCircle(15, 7, 4, 13, -90, "192.168.2.123");
joinComps(comps, hub2, 0, 2, "192.168.2.123");

