package jnet.client.gui;

import jnet.client.Client;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.Base64;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JTable;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumn;
import jnet.lib.object.ObjectType;

public class TableDeviceType extends JTable {
    

    private static final String[] COLUMN_NAMES = {
        "Ikona",
        "Název zařízení"};

    public TableDeviceType() {
        
        tableSetup();

    }

    @Override
    public Class<?> getColumnClass(int column) {
        if (column == 0) {
            return ImageIcon.class;
        } else {
            return String.class;
        }
    }

    private void tableSetup() {
        DefaultTableModel model = new DefaultTableModel(COLUMN_NAMES, Client.objectType.size()) {
            @Override
            public boolean isCellEditable(int row, int column) {
                //all cells false
                return false;
            }
            
        };

        this.setModel(model);

        DefaultTableCellRenderer dtcr = new DefaultTableCellRenderer();
        dtcr.setHorizontalAlignment(DefaultTableCellRenderer.CENTER);
        this.setDefaultRenderer(String.class, dtcr);

        int row = 0;
        for (ObjectType obj : Client.objectType) {
            try {
                byte[] decodedBytes = Base64.getDecoder().decode(obj.getImgStr());
                ByteArrayInputStream bis = new ByteArrayInputStream(decodedBytes);
                ImageIcon icon = new ImageIcon(ImageIO.read(bis));
                this.setValueAt(icon, row, 0);
                this.setValueAt(obj.getName(), row, 1);
                row++;
            } catch (IOException ex) {
                Logger.getLogger(TableDeviceType.class.getName()).log(Level.SEVERE, null, ex);
            }
        }

        // nastavení vysky radku
        for (int i = 0; i < Client.objectType.size(); i++) {
            this.setRowHeight(i, this.getRowHeight(i) + 40);
        }

        // nastavení sirky sloupce
        for (int i = 0; i < COLUMN_NAMES.length; i++) {
            TableColumn column = this.getColumnModel().getColumn(i);
            column.setPreferredWidth(column.getPreferredWidth() + 80);
        }

        this.setVisible(true);
    }
}
