var fs = require("fs");
var exec = require('child_process').exec;

var text = fs.readFileSync("/home/csserver/serverfiles/cstrike/mapcycle.txt").toString('utf-8');
var maps = text.split("\n").filter(String)
var mapsBak = [...maps]
var currMapcycle = [...maps];
var notListed = new Array();
var i = 0;
var mapsLocation = './serverfiles/cstrike/maps/';

console.log(maps);


restart();

function deleteMap(map) {
    fs.readdir(mapsLocation, (err, files) => {
        files.forEach(file => {
            if(file.split('.')[0] == map) {
                console.log(`Deleted ${mapsLocation + file}`); 
                fs.unlinkSync( mapsLocation + file ); 
            }       
        });
    });
    
}

function checkMaps() {
    var map = maps[i];

    execute(`/home/csserver/csserver send "changelevel ${map}"`, function(changelevel) {
        console.log(`\n\n${"-".repeat(80)}\n[${i+1} / ${maps.length}] ${map}`);
        //console.log(`[${i+1} / ${maps.length+1}]`);
        console.log(changelevel);
        setTimeout(details, 5000);  
    });  
}

function reset() {
    i = 0;
    text = fs.readFileSync("/home/csserver/serverfiles/cstrike/mapcycle.txt").toString('utf-8');
    maps = text.split("\n").filter(String);
    restart();
}

function details() {
    execute("/home/csserver/csserver details", function(details) {
        //console.log(details);

        currMapcycle.shift();

        if (details.match(/not listed/)) {
            console.log("Master server: not listed");
            notListed.push(maps[i]);


            writeFile(notListed, 'notListed.txt');


            console.log(currMapcycle);
            writeFile(currMapcycle, './serverfiles/cstrike/mapcycle.txt');            
            deleteMap(maps[i]);
            removeByValue(mapsBak, maps[i]);
            console.log(mapsBak);
            setTimeout(reset, 5000);

            //throw new Error("Exiting on purpose");
        }
        else if (details.match(/listed/)) {
            console.log("Master server: listed");
            
            i++;            
            i < maps.length ? checkMaps() : finish();
        }
    });
}

function removeByValue(array, item) {    
    var index = array.indexOf(item);
    if (index !== -1) {
        array.splice(index, 1);
    }
    console.log(`Removed ${item} from map pool.`);
}

function writeFile(arr, file) {
    const writeStream = fs.createWriteStream(file);
    const pathName = writeStream.path;
    
    // write each value of the array on the file breaking line
    arr.forEach(value => writeStream.write(`${value}\n`));

    // the finish event is emitted when all data has been flushed from the stream
    writeStream.on('finish', () => {
        console.log(`wrote all the array data to file ${pathName}`);
    });

    // handle the errors on the write process
    writeStream.on('error', (err) => {
        console.error(`There is an error writing the file ${pathName} => ${err}`)
    });

    // close the stream
    writeStream.end();
}

function sleep(ms) {
    return new Promise(resolve => setTimeout(resolve, ms));
}

function finish() {
    console.log("Finish");
    writeFile(mapsBak, './serverfiles/cstrike/mapcycle.txt');
}

function restart() {
    console.log("Restarting...");
    execute("/home/csserver/csserver restart", function(restart) {
		console.log(restart);
        checkMaps();
	});    
}

function execute(command, callback){
    exec(command, function(error, stdout, stderr) { callback(stdout); });
};