package de.duehl.swing.ui.highlightingeditor.gotoline;

/*
 * Copyright 2017 Christian Dühl. All rights reserved.
 *
 * This program is free software. You can redistribute it and/or
 * modify it under the same terms as perl:
 *
 * general:  http://dev.perl.org/licenses/
 * GPL:      http://dev.perl.org/licenses/gpl1.html
 * artistic: http://dev.perl.org/licenses/artistic.html
 */

import de.duehl.basics.text.NumberString;
import de.duehl.basics.text.Text;
import de.duehl.swing.ui.highlightingeditor.HighlightingEditor;

/**
 * Diese Klasse kümmert sich um die Suche im Editor.
 *
 * @version 1.01     2017-12-15
 * @author Christian Dühl
 */

public class GotoLine {

    /** Der Editor in dem Zeilen angesprungen werden. */
    private HighlightingEditor editor;

    /**
     * Konstruktor.
     *
     * Achtung, wird dieser Konstruktor verwendet, muss vor der Benutzung der
     * Editor mit switchEditor() gesetzt werden!
     */
    public GotoLine() {
    }

    /**
     * Konstruktor
     *
     * @param editor
     *            Editor in dem Zeilen angesprungen werden.
     */
    public GotoLine(HighlightingEditor editor) {
        this.editor = editor;
    }

    public void switchEditor(HighlightingEditor editor) {
        this.editor = editor;
    }

    public void gotoLine(String text) {
        if (!text.isEmpty() && NumberString.isDigitSequence(text)) {
            gotoLine(NumberString.parseIntIgnore(text, 0));
        }
    }

    private void gotoLine(int lineNumber) {
        if (lineNumber >= 1) {
            int startPositon = determineStartPositionOfSentence(lineNumber);
            editor.setCaretPosition(startPositon);
        }
    }

    private int determineStartPositionOfSentence(int lineNumber) {
        if (lineNumber == 1) {
            return 0;
        }

        int lineNumberZeroBased = lineNumber - 1;
        String text = getTextWithInternalLineBreaks();

        int index = 0;
        int found = 0;
        int lastIndex;

        while (index != -1 && found < lineNumberZeroBased) {
            lastIndex = index;
            index = text.indexOf("\n", index) + "\n".length();
            if (index < lastIndex) {
                return text.length();
            }
            ++found;
        }

        return index;
    }

    private String getTextWithInternalLineBreaks() {
        String text = editor.getText();
        text = Text.lineBreaksToBackslashN(text);
        return text;
    }

}
