/*
  THIS FILE WAS AUTOGENERATED BY mode.tmpl.js
*/

"use strict";

var oop = require("../lib/oop");
var TextMode = require("./text").Mode;
var VBScriptHighlightRules = require("./vbscript_highlight_rules").VBScriptHighlightRules;
var FoldMode = require("./folding/vbscript").FoldMode;
var Range = require("../range").Range;

var Mode = function() {
    this.HighlightRules = VBScriptHighlightRules;
    this.foldingRules = new FoldMode();
    this.$behaviour = this.$defaultBehaviour;
    this.indentKeywords = this.foldingRules.indentKeywords;
};
oop.inherits(Mode, TextMode);

(function() {

    this.lineCommentStart = ["'", "REM"];

    var outdentKeywords = [
        "else",
        "elseif",
        "end",
        "loop",
        "next",
        "wend"
    ];

    function isSecondOfDoubleKeyword(tokens, i) {
        var val = tokens[i].value.toLowerCase();
        var prevToken = i >= 2 ? tokens[i - 2] : null;
        if (!prevToken) return false;
        var prevVal = prevToken.value.toLowerCase();

        // Do While / Do Until / Loop While / Loop Until
        if ((val === "while" || val === "until") && (prevVal === "do" || prevVal === "loop")) {
            return true;
        }
        // Exit For / Exit Do / Exit Sub / Exit Function / Exit Property
        if (prevVal === "exit" && (val === "for" || val === "do" || val === "sub" || val === "function" || val
            === "property")) {
            return true;
        }
        return false;
    }

    function getNetIndentLevel(tokens, line, indentKeywords) {
        var level = 0;
        // Support single-line blocks by decrementing the indent level if
        // an ending token is found
        for (var i = 0; i < tokens.length; i++) {
            var token = tokens[i];
            if (token.type == "keyword.control.asp" || token.type == "storage.type.function.asp") {
                var val = token.value.toLowerCase();
                if (val in indentKeywords) {
                    if (isSecondOfDoubleKeyword(tokens, i)) {
                        continue;
                    }
                    switch (val) {
                        case "property":
                        case "sub":
                        case "function":
                        case "select":
                        case "do":
                        case "for":
                        case "class":
                        case "while":
                        case "with":
                        case "if":
                            var checkToken = new RegExp("^\\s* end\\s+" + val, "i");
                            var singleLineCondition = /^\s*If\s+.*\s+Then(?!')\s+(?!')\S/i.test(line);
                            if (!singleLineCondition && !checkToken.test(line))
                                level += indentKeywords[val];
                            break;
                        default:
                            level += indentKeywords[val];
                            break;
                    }
                }
            }
        }
        // Limit the level to +/- 1 since usually users only indent one level
        // at a time regardless of the logical nesting level
        if (level < 0) {
            return -1;
        } else if (level > 0) {
            return 1;
        } else {
            return 0;
        }
    }

    this.getNextLineIndent = function(state, line, tab) {
        var indent = this.$getIndent(line);
        var level = 0;

        var tokenizedLine = this.getTokenizer().getLineTokens(line, state);
        var tokens = tokenizedLine.tokens;

        if (state == "start") {
            level = getNetIndentLevel(tokens, line, this.indentKeywords);
        }
        if (level > 0) {
            return indent + tab;
        } else if (level < 0 && indent.substr(indent.length - tab.length) == tab) {
            // Don't do a next-line outdent if we're going to do a real outdent of this line
            if (!this.checkOutdent(state, line, "\n")) {
                return indent.substr(0, indent.length - tab.length);
            }
        }
        return indent;
    };

    this.checkOutdent = function(state, line, input) {
        if (input != "\n" && input != "\r" && input != "\r\n")
            return false;

        var tokens = this.getTokenizer().getLineTokens(line.trim(), state).tokens;

        if (!tokens || !tokens.length)
            return false;
        var val = tokens[0].value.toLowerCase();
        return ((tokens[0].type == "keyword.control.asp" || tokens[0].type == "storage.type.function.asp") && outdentKeywords.indexOf(val) != -1);
    };

    this.getMatching = function(session, row, column, tokenRange) {
        if (row == undefined) {
            var pos = session.selection.lead;
            column = pos.column;
            row = pos.row;
        }
        if (tokenRange == undefined)
            tokenRange = true;

        var startToken = session.getTokenAt(row, column);
        if (startToken) {
            var val = startToken.value.toLowerCase();
            if (/^\s+$/.test(val)) {
                column = column + val.length;
                startToken = session.getTokenAt(row, column);
                if (!startToken) {
                    return;
                }
                val = startToken.value.toLowerCase();
            }
            if (val in this.indentKeywords)
                return this.foldingRules.vbsBlock(session, row, column, tokenRange);
        }
    };

    this.autoOutdent = function(state, session, row) {
        var line = session.getLine(row);
        var column = line.match(/^\s*/)[0].length;
        if (!column || !row) return;

        var startRange = this.getMatching(session, row, column + 1, false);
        if (!startRange || startRange.start.row == row)
            return;
        var indent = this.$getIndent(session.getLine(startRange.start.row));
        if (indent.length != column) {
            session.replace(new Range(row, 0, row, column), indent);
            session.outdentRows(new Range(row + 1, 0, row + 1, 0));
        }
    };

    this.$id = "ace/mode/vbscript";
}).call(Mode.prototype);

exports.Mode = Mode;
