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

/*
 * 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 java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

import javax.swing.JMenuItem;
import javax.swing.JPopupMenu;

/**
 * Diese Klasse stellt das Popupmenü für den bearbeitbaren Editors mit Syntax-Highlighting dar.
 *
 * @version 1.01     2017-12-05
 * @author Christian Dühl
 */

public class EditorPopupMenu extends JPopupMenu {

    private static final long serialVersionUID = 1L;

    private final EditorForContextMenu editor;

    private JMenuItem cutItem;

    private JMenuItem copyItem;

    private JMenuItem insertItem;

    public EditorPopupMenu(EditorForContextMenu editor) {
        super();
        this.editor = editor;
        editor.addMouseListener(createMouseAdapter());

        add(createCutSelectionMenuItem());
        add(createCopySelectionMenuItem());
        add(createInsertSelectionMenuItem());

        addSeparator();

        add(createSelectAllMenuItem());
    }

    private MouseAdapter createMouseAdapter() {
        return new MouseAdapter()        {
            @Override
            public void mousePressed(MouseEvent event)
            {
                handleContextMenu();
            }

            @Override
            public void mouseReleased(MouseEvent event)
            {
                handleContextMenu();
            }
        };
    }

    private void handleContextMenu() {
        String selection = editor.getSelectedText();
        boolean nothingSelected = null == selection || selection.isEmpty();
        cutItem.setEnabled(!nothingSelected);
        copyItem.setEnabled(!nothingSelected);
    }

    private JMenuItem createCutSelectionMenuItem() {
        JMenuItem item = new JMenuItem("Ausschneiden");
        item.addActionListener(e -> editor.cutSelection());
        this.cutItem = item;
        return item;
    }

    private JMenuItem createCopySelectionMenuItem() {
        JMenuItem item = new JMenuItem("Kopieren");
        item.addActionListener(e -> editor.copySelection());
        this.copyItem = item;
        return item;
    }

    private JMenuItem createInsertSelectionMenuItem() {
        JMenuItem item = new JMenuItem("Einfügen");
        item.addActionListener(e -> editor.insertSelection());
        this.insertItem = item;
        return item;
    }

    private JMenuItem createSelectAllMenuItem() {
        JMenuItem item = new JMenuItem("Alles auswählen");
        item.addActionListener(e -> editor.selectAll());
        return item;
    }

    public void deactivateInsertMenuItem() {
        insertItem.setEnabled(false);
    }

}
