package org.ui.editors.code;

import javax.swing.*;
import javax.swing.text.Element;
import java.awt.*;

public class JLineNumberTextPane extends JTextArea {
    private static final long serialVersionUID = -2596467098026617439L;
    private JTextPane textPane;

    public JLineNumberTextPane(JTextPane textPane) {
        this.textPane = textPane;

        setFont(new Font("Consolas", 0, 16));
        setEditable(false);
        setBorder(BorderFactory.createCompoundBorder(BorderFactory.createMatteBorder(0, 0, 0, 1, getBackground().darker()), BorderFactory.createEmptyBorder(0, 12, 0, 16)));
    }

    public final void updateLineNumbers() {
        setText(getLineNumbersText());
    }

    private String getLineNumbersText() {
        Integer caretPosition = Integer.valueOf(this.textPane.getDocument().getLength());

        Element root = this.textPane.getDocument().getDefaultRootElement();

        StringBuilder textBuilder = new StringBuilder();

        textBuilder.append("1").append(System.lineSeparator());

        for (int elementIndex = 2; elementIndex < root.getElementIndex(caretPosition.intValue()) + 2; elementIndex++) {
            textBuilder.append(elementIndex).append(System.lineSeparator());
        }
        return textBuilder.toString();
    }
}
