package Common.Visual.Tables;
import Common.MainModule_;
import Common.Visual.Fonts.VisualiserFonts;
import Common.Visual.Menus.TableMenu;
import Common.Visual.Themes.ThemeElement;

import javax.swing.*;
import javax.swing.table.*;
import java.awt.*;
public abstract class StyledTable extends JTable implements ThemeElement {
    //https://askdev.ru/q/kak-upravlyat-stilem-cvetom-i-razmerom-shrifta-vnutri-jtable-455196/
    //https://stackoverflow.com/questions/4129666/how-to-convert-hex-to-rgb-using-java цвета
    public StyledTable(AbstractTableModel model) {
        super(model);
        setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
        setFillsViewportHeight(true);
        setAutoCreateRowSorter(dataModel.getRowCount() > 0);
        Init();
        setFont(MainModule_.instance.getUI().getTheme().Fonts.get(VisualiserFonts.TreePlain));
        JTableHeader header = getTableHeader();
        header.setFont(MainModule_.instance.getUI().getTheme().Fonts.get(VisualiserFonts.TreePlain));
        putClientProperty("terminateEditOnFocusLost", Boolean.TRUE);
        setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        //текущий объет может определяться по первому столбцу. могут быть баги если не запретить
        getTableHeader().setReorderingAllowed(false);
        CorrectSizes();
        setComponentPopupMenu(CreateMenu());
        applyTheme();
    }
    public TableMenu CreateMenu() {
        return new TableMenu(this);
    }
    public void Init() {
    }
    private void adjustColumnSizes(int column, int margin) {
        DefaultTableColumnModel colModel = (DefaultTableColumnModel) getColumnModel();
        TableColumn col = colModel.getColumn(column);
        int width;
        TableCellRenderer renderer = col.getHeaderRenderer();
        if (renderer == null) {
            renderer = getTableHeader().getDefaultRenderer();
        }
        Component comp = renderer.getTableCellRendererComponent(this, col.getHeaderValue(), false, false, 0, 0);
        width = comp.getPreferredSize().width;
        for (int r = 0; r < getRowCount(); r++) {
            renderer = getCellRenderer(r, column);
            comp = renderer.getTableCellRendererComponent(this, getValueAt(r, column), false, false, r, column);
            int currentWidth = comp.getPreferredSize().width;
            width = Math.max(width, currentWidth);
        }
        width += 2 * margin;
        col.setPreferredWidth(width);
        col.setWidth(width);
    }
    private void adjustJTableRowSizes() {
        for (int row = 0; row < getRowCount(); row++) {
            int maxHeight = 0;
            for (int column = 0; column < getColumnCount(); column++) {
                TableCellRenderer cellRenderer = getCellRenderer(row, column);
                Object valueAt = getValueAt(row, column);
                Component tableCellRendererComponent = cellRenderer.getTableCellRendererComponent(this, valueAt, false, false, row, column);
                int heightPreferable = tableCellRendererComponent.getPreferredSize().height;
                maxHeight = Math.max(heightPreferable, maxHeight);
            }
            setRowHeight(row, maxHeight);
        }
    }
    public void CorrectSizes() {
        adjustJTableRowSizes();
        CorrectColumnsSizes();
        this.removeEditor();//отлючение редактирования клеток если таковые были.
    }
    public void CorrectColumnsSizes() {
        for (int i = 0; i < getColumnCount(); i++) {
            adjustColumnSizes(i, 2);
        }
    }
    @Override
    public void applyTheme() {
        setBackground(MainModule_.instance.getUI().getTheme().table_background);
        setForeground(MainModule_.instance.getUI().getTheme().foreground);
        setSelectionBackground(MainModule_.instance.getUI().getTheme().selection_background);
        setSelectionForeground(MainModule_.instance.getUI().getTheme().foreground);
    }
    public void SelectRow(int r) {
        getSelectionModel().setSelectionInterval(r, r);
    }
    public void scrollToVisible(int rowIndex, int vColIndex) {
        if (!(getParent() instanceof JViewport)) {
            return;
        }
        JViewport viewport = (JViewport) getParent();
        Rectangle rect = getCellRect(rowIndex, vColIndex, true);
        Point pt = viewport.getViewPosition();
        rect.setLocation(rect.x - pt.x, rect.y - pt.y);
        viewport.scrollRectToVisible(rect);
    }
    public void scrollToLastRow() {
        scrollToVisible(getRowCount() - 1, 0);
    }
}
