import * as vscode from 'vscode';

export class BlockDetector {
    constructor(private editor : vscode.TextEditor) {
    }

    public detect() {
        const position = this.editor.selection.active;
        const doc = this.editor.document;

        let startLine = doc.lineAt(position.line-1);
        let endLine = doc.lineAt(position.line);

        while (!startLine.isEmptyOrWhitespace && startLine.lineNumber > 0) {
            startLine = doc.lineAt(startLine.lineNumber-1)
        }
        if (startLine.isEmptyOrWhitespace) {
            startLine = doc.lineAt(startLine.lineNumber+1)
        }

        let createMatch = startLine.text.match(/create\s+(or\s+replace\s+)?(\w+)\s+(\S+)/)
        if (createMatch) {
            while (!endLine.text.match("end " + createMatch[3] + ";") && endLine.lineNumber < doc.lineCount-1) {
                endLine = this.editor.document.lineAt(endLine.lineNumber+1)
            }
        } else {
            while (!endLine.text.match(/;/) && endLine.lineNumber < doc.lineCount-1) {
                endLine = this.editor.document.lineAt(startLine.lineNumber+1)
            }
        }
        
        this.editor.selection = new vscode.Selection(new vscode.Position(startLine.lineNumber, 0), new vscode.Position(endLine.lineNumber, endLine.text.length))
    }
}