/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package vermilion;

import java.awt.Color;
import java.awt.Component;
import javax.swing.JLabel;
import javax.swing.JTable;
import javax.swing.table.TableCellRenderer;

/**
 *
 * @author LocalGuy
 */
public class JPatternTableCellRenderer implements TableCellRenderer
{
    // Colors we use to show different cell states.
    private Color normalColor = new Color(255, 255, 255);
    private Color timeSigColor = new Color(230, 230, 255);
    private Color selectedColor = new Color(230, 255, 230);
    private Color cursorColor = new Color(255, 230, 230);

    /**
     * This is where we return the component for rendering a cell. We handle
     * several things here including selection and cursor as well as content.
     */
    @Override
    public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column)
    {
        // TODO: Cache these labels for the current pattern?
        String text = (String) value;
        JLabel label = new JLabel(text, JLabel.CENTER);
        label.setOpaque(true);
        label.setFont(table.getFont());

        // TODO: Read time sig of pattern.
        int timeSig = 4;

        // For some reason asking JTable what cell is selected simply does not
        // work. We have to manually check which columns are selected.
        boolean colSelect = false;
        for (int x = 0; x < table.getSelectedColumnCount(); x++)
        {
            if (table.getSelectedColumns()[x] == column) colSelect = true;
        }

        if (hasFocus)
        {
            label.setBackground(cursorColor);
            
            JPatternTable jTable = ((JPatternTable) table);

            // HACK: Hackity hack hack, hackity hack hack.
            if (jTable.columnPosition >= jTable.columns[column].columnWidth)
            {
                jTable.columnPosition = jTable.columns[column].columnWidth - 1;
            }

            // TODO: Is this necessary? (UPDATE: Yes) It isn't wise!
            jTable.gridX = column;
            jTable.gridY = row;

            // TODO: Better cursor.
            char[] arr = text.toCharArray();
            arr[jTable.columnPosition] = '#';
            label.setText(new String(arr));

        }
        // Here is where we check the cell is selected.
        else if (isSelected && colSelect)
        {
            label.setBackground(selectedColor);
        }
        else
        {
            if (row % timeSig == 0) //if it's first beat
            {
                label.setBackground(timeSigColor);
            }
            else
            {
                label.setBackground(normalColor);
            }
        }

        return label;
    }
}