package de.duehl.swing.ui.tables;

/*
 * 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.Component;
import java.awt.Container;
import java.awt.event.FocusAdapter;
import java.awt.event.FocusEvent;

import javax.swing.DefaultCellEditor;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.border.EmptyBorder;
import javax.swing.table.TableCellEditor;

public class CellFocusLoosingTable extends JTable {

    private static final long serialVersionUID = 1L;

    public CellFocusLoosingTable() {
        addLoosingCellEditor();
        addLoosingFocusListener();
    }

    private void addLoosingCellEditor() {
        JTextField editorField = createCellEditorField();
        DefaultCellEditor editor = new DefaultCellEditor(editorField);
        setDefaultEditor(Object.class, editor);
    }

    private JTextField createCellEditorField() {
        JTextField editorField = new JTextField(10);
        editorField.setBorder(new EmptyBorder(1, 1, 1, 1));
        editorField.addFocusListener(new FocusAdapter() {
            @Override
            public void focusLost(FocusEvent event) {
                editorFocusLost(event);
            }
        });
        return editorField;
    }

    private void editorFocusLost(FocusEvent event) {
        TableCellEditor cellEditor = getCellEditor();
        if (cellEditor != null) {
            if (!cellEditor.stopCellEditing()) {
                cellEditor.cancelCellEditing();
            }
        }

        Component gotFocus = event.getOppositeComponent();
        if (!this.equals(gotFocus)) {
            clearSelection();
        }
    }

    private void addLoosingFocusListener() {
        addFocusListener(new FocusAdapter() {
            @Override
            public void focusLost(FocusEvent event) {
                tableFocusLost(event);
            }
            @Override
            public void focusGained(FocusEvent event) {
                // nix
            }
        });
    }

    private void tableFocusLost(FocusEvent event) {
//        getSelectionModel().clearSelection(); Auch nicht.
//
        Component gotFocus = event.getOppositeComponent();
        if (gotFocus != null) {
            Container parent = gotFocus.getParent();
            if (parent != null) {
                if (!parent.equals(this)) {
                    TableCellEditor cellEditor = getCellEditor();
                    if (cellEditor != null) {
                        if (!cellEditor.stopCellEditing()) {
                            cellEditor.cancelCellEditing();
                        }
                    }
                    clearSelection();
                }
            }
        }
    }

}
