/*
 * Copyright (c) 2024. Elex. All Rights Reesrved.
 * https://www.elex-project.com/
 */

package com.elex_project.examples.components;

import javax.swing.*;
import javax.swing.event.CaretEvent;
import javax.swing.event.CaretListener;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.text.Document;
import javax.swing.undo.UndoManager;
import java.awt.*;
import java.awt.event.ActionEvent;

public class DocumentListenerExample extends JPanel {

	DocumentListenerExample() {
		super(new BorderLayout());

		// UndoableEditListener
		// 레이아웃 구성
		final JToolBar toolBar = new JToolBar();
		final JTextArea textArea = new JTextArea();
		this.add(toolBar, BorderLayout.NORTH);
		this.add(textArea, BorderLayout.CENTER);

		// 언두 매니저를 생성하고, 텍스트 문서에 리스너를 통해 연결한다.
		final UndoManager undoManager = new UndoManager();
		textArea.getDocument().addUndoableEditListener(undoableEditEvent ->
				undoManager.addEdit(undoableEditEvent.getEdit()));

		// 버튼을 통해서 액션을 처리한다.
		toolBar.add(new AbstractAction("Undo") {
			@Override
			public void actionPerformed(ActionEvent actionEvent) {
				if (undoManager.canUndo()) {
					undoManager.undo();
				}
			}
		});
		toolBar.add(new AbstractAction("Redo") {
			@Override
			public void actionPerformed(ActionEvent actionEvent) {
				if (undoManager.canRedo()) {
					undoManager.redo();
				}
			}
		});

		// DocumentListener
		textArea.getDocument().addDocumentListener(new DocumentListener() {
			@Override
			public void insertUpdate(DocumentEvent documentEvent) {
				Document document = documentEvent.getDocument();
				int changeLength = documentEvent.getLength();
			}

			@Override
			public void removeUpdate(DocumentEvent documentEvent) {

			}

			@Override
			public void changedUpdate(DocumentEvent documentEvent) {

			}
		});

		// CaretListener
		textArea.addCaretListener(new CaretListener() {
			@Override
			public void caretUpdate(CaretEvent caretEvent) {
				int dot = caretEvent.getDot();
				int mark = caretEvent.getMark();
			}
		});
	}

	public static void main(String... args) {

		final JFrame jFrame = new JFrame();
		jFrame.setTitle("Example");
		jFrame.setSize(800, 600);
		jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		jFrame.setContentPane(new DocumentListenerExample());

		SwingUtilities.invokeLater(() -> jFrame.setVisible(true));

	}
}
