module DialogueTrees {
    // let trees : {[name : string] : DialogueTree} = {};
    //
    // export function addTree(tree : DialogueTree) {
    //     trees[tree.id] = tree;
    // }

    /**
     * This prints information about usage of every DialogueTree available.
     * Note: Even though a DialogueTree is referenced, it *might* still not be accessible if the code leading to it is faulty.
     * This should be used to know whether or not a DialogueTree was "forgotten", since the IDE can only do this manually.
     */
    export function findUnusedTrees () {
        let allCode = document.getElementById("appCode").innerHTML;

        let useCount = {};
        let unused = [];

        for (let dialogueName in DialogueTrees) {
            if (dialogueName != "findUnusedTrees") {
                // The first mention will be the one defining it to exist, so we need at least two occurrences for it to be used.
                let count = occurrences(allCode, "DialogueTrees." + dialogueName, false) - 1;
                if (count > 0) {
                    useCount[dialogueName] = count;
                } else {
                    unused.push(dialogueName);
                }
            }
        }

        for (let dialogueName in useCount) {
            let times = useCount[dialogueName];
            console.debug("[DialogueUsage] " + dialogueName + " is referenced " + times + (times > 1 ? " times." : " time."));
        }

        for (let i = 0; i < unused.length; i++) {
            console.error("[DialogueUsage] " + unused[i] + " is never referenced and will not appear in-game.");
        }
    }

    /** Function that count occurrences of a substring in a string;
     * @param {String} string               The string
     * @param {String} subString            The sub string to search for
     * @param {Boolean} [allowOverlapping]  Optional. (Default:false)
     *
     * @author Vitim.us https://gist.github.com/victornpb/7736865
     * @see Unit Test https://jsfiddle.net/Victornpb/5axuh96u/
     * @see http://stackoverflow.com/questions/4009756/how-to-count-string-occurrence-in-string/7924240#7924240
     */
    function occurrences(string, subString, allowOverlapping) {

        string += "";
        subString += "";
        if (subString.length <= 0) return (string.length + 1);

        var n = 0,
            pos = 0,
            step = allowOverlapping ? 1 : subString.length;

        while (true) {
            pos = string.indexOf(subString, pos);
            if (pos >= 0) {
                ++n;
                pos += step;
            } else break;
        }
        return n;
    }
}