package ca.odell.glazedlists.example;

import ca.odell.glazedlists.BasicEventList;
import ca.odell.glazedlists.EventList;
import ca.odell.glazedlists.GlazedLists;
import ca.odell.glazedlists.SortedList;
import ca.odell.glazedlists.gui.TableFormat;
import ca.odell.glazedlists.swing.EventTableModel;
import ca.odell.glazedlists.swing.TableComparatorChooser;
import ca.odell.glazedlists.swing.SortableRenderer;

import javax.swing.*;
import javax.swing.table.TableCellRenderer;
import java.awt.*;

public class CustomTableHeaderRendererExample {

    public static void main(String[] args) {
        final EventList<Color> colors = new BasicEventList<Color>();
        colors.add(Color.ORANGE);
        colors.add(Color.DARK_GRAY);
        colors.add(Color.LIGHT_GRAY);

        final SortedList<Color> sortedColors = new SortedList<Color>(colors, null);

        final String[] propertyNames = new String[] {"red", "green", "blue"};
        final String[] columnLabels = new String[] {"Red\nStuff", "Green\nStuff", "Blue\nStuff"};
        final TableFormat<Color> tf = GlazedLists.tableFormat(Color.class, propertyNames, columnLabels);
        final JTable t = new JTable(new EventTableModel<Color>(sortedColors, tf));

        t.getTableHeader().setDefaultRenderer(new MultiLineHeaderRenderer());

        new TableComparatorChooser<Color>(t, sortedColors, true);

        final JFrame f = new JFrame();
        f.setLayout(new BorderLayout());
        f.add(new JScrollPane(t), BorderLayout.CENTER);

        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.pack();
        f.setLocationRelativeTo(null);
        f.setVisible(true);
    }

    private static class MultiLineHeaderRenderer extends JPanel implements TableCellRenderer, SortableRenderer {

        private final JList lineList = new JList();
        private final JLabel iconLabel = new JLabel();

        public MultiLineHeaderRenderer() {
            super(new BorderLayout());

            setBorder(UIManager.getBorder("TableHeader.cellBorder"));

            lineList.setBackground(UIManager.getColor("TableHeader.background"));
            iconLabel.setBackground(UIManager.getColor("TableHeader.background"));

            final JLabel renderer = (JLabel) lineList.getCellRenderer();
            renderer.setHorizontalAlignment(JLabel.CENTER);

            add(lineList, BorderLayout.CENTER);
            add(iconLabel, BorderLayout.EAST);
        }

        public void setSortIcon(Icon sortIcon) {
            iconLabel.setIcon(sortIcon);
        }

        public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
            final String[] lines = value.toString().split("\n");
            lineList.setListData(lines);
            return this;
        }
    }
}