var scriptName = "FileSpammer";
var scriptAuthor = "Senk Ju";
var scriptVersion = 1.0;

var File = Java.type("java.io.File");
var FileReader = Java.type("java.io.FileReader");
var BufferedReader = Java.type("java.io.BufferedReader");
var FileWriter = Java.type("java.io.FileWriter");
var BufferedWriter = Java.type("java.io.BufferedWriter");
var Timer = Java.type("java.util.Timer");

var config = {
    spamFilePath: "",
    spamDelay: 1000,
    appendRandom: true
}

var chatPrefix = "§8[§9FileSpam§8]";

function log(message, isError) {
    if (isError) {
        chat.print(chatPrefix + " §c" + message);
    } else {
        chat.print(chatPrefix + " §f" + message);
    }
}

function readFile(filePath) {
    try {
        var file = new File(filePath);
        var reader = new BufferedReader(new FileReader(file));
        var content = [];
        var line;

        while ((line = reader.readLine()) !== null) {
            content.push(line);
        }

        return content;
    } catch (err) {
        log("Unable to open file!", true);

        throw err;
    }
}

function writeFile(path, string) {
    try {
        writer = new BufferedWriter(new FileWriter(path));
        writer.write(string);

        writer.close();
    } catch (err) {}
}

function saveConfig() {
    var configJSON = JSON.stringify(config);

    writeFile(mc.mcDataDir + "/filespammer.json", configJSON);
}

function loadConfig() {
    try {
        config = JSON.parse(readFile(mc.mcDataDir + "/filespammer.json").join(""));
    } catch (err) {}
}

function randomString(length) {
    var text = "";
    var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";

    for (var i = 0; i < length; i++) {
        text += possible.charAt(Math.floor(Math.random() * possible.length));
    }

    return text;
}

function setInterval(func, milliseconds) {
    var timer = new Timer("setInterval", true);

    timer.schedule(function () {
        func();
    }, milliseconds, milliseconds);

    return timer;
}

function clearInterval(timer) {
    timer.cancel();
}

function setTimeout(func, milliseconds) {
    var timer = new Timer("setTimeout", true);
    timer.schedule(function () {
        func();
    }, milliseconds);

    return timer;
}

function FileSpammerModule() {
    var spamInterval;

    this.getName = function () {
        return "FileSpammer";
    }

    this.getDescription = function () {
        return "Spams the chat from a text file.";
    };

    this.getCategory = function () {
        return "Misc";
    }

    this.onEnable = function () {
        if (!config.spamFilePath) {
            log("Please specify a spam file using '.filespammer path <path>' before enabling this module!", true);

            var spamFileModule = moduleManager.getModule(this.getName());

            setTimeout(function () {
                spamFileModule.setState(false);
            }, 100);

            return;
        }

        var spamFile = readFile(config.spamFilePath);
        var spamIndex = 0;

        spamInterval = setInterval(function () {
            if (config.appendRandom) {
                mc.thePlayer.sendChatMessage(spamFile[spamIndex] + " [" + randomString(8) + "]");
            } else {
                mc.thePlayer.sendChatMessage(spamFile[spamIndex]);
            }

            if (spamIndex < spamFile.length - 1) {
                spamIndex++;
            } else {
                spamIndex = 0;
            }
        }, config.spamDelay);
    }

    this.onDisable = function () {
        clearInterval(spamInterval);
    }
}

function FileSpammerCommand() {
    this.getName = function () {
        return "filespammer";
    }

    this.getAliases = function () {
        return ["fs"];
    }

    this.execute = function (args) {
        if (args.length < 2) {
            log("Syntax Error: .filespammer <path/delay/appendRandom>", true);
            return;
        }

        switch (args[1].toLowerCase()) {
            case "path":
                if (args.length < 3) {
                    log("Syntax Error: .filespammer path <path>", true);
                    return;
                }

                config.spamFilePath = args[2];
                log("Set FileSpammer path to " + config.spamFilePath, false);
                saveConfig();

                break;

            case "delay":
                if (args.length < 3) {
                    log("Syntax Error: .filespammer delay <ms>", true);
                    return;
                }

                var input = parseInt(args[2]);

                if (input < 0) {
                    log("Please enter a value higher than 0", true);
                    return;
                }

                config.spamDelay = input;
                log("Set FileSpammer delay to " + input, false);
                saveConfig();

                break;

            case "appendrandom":
                config.appendRandom = !config.appendRandom;
                log("Set FileSpammer appendRandom to " + config.appendRandom, false);
                saveConfig();

                break;

            default:
                log("Syntax Error: .filespammer <path/delay/appendRandom>", true);
        }
    }
}

var fileSpammerModule = new FileSpammerModule();
var fileSpammerCommand = new FileSpammerCommand();

var fileSpammerModuleClient;
var fileSpammerCommandClient;

function onEnable() {
    loadConfig();

    fileSpammerModuleClient = moduleManager.registerModule(fileSpammerModule);
    fileSpammerCommandClient = commandManager.registerCommand(fileSpammerCommand);
}

function onDisable() {
    moduleManager.unregisterModule(fileSpammerModuleClient);
    commandManager.unregisterCommand(fileSpammerCommandClient);
}