/*
 * ClipboardString.java
 *
 * Created on June 29, 2006, 2:53 PM
 *
 * To change this template, choose Tools | Template Manager
 * and open the template in the editor.
 */

package usda.weru.util.table;

import com.klg.jclass.table.DataViewModel;
import com.klg.jclass.table.JCCellDisplayEvent;
import com.klg.jclass.table.JCCellRange;
import com.klg.jclass.table.JCTable;
import com.klg.jclass.table.JCTableEnum;
import java.awt.datatransfer.StringSelection;

/**
 * Wrapper class to handle copying table data to the clipboard.
 * @author Joseph Levin
 */
public class ClipboardString extends StringSelection{    
    /**
     * Creates a new instance of ClipboardString.
     * @param table The WepsTable containing cells to be copied to the clipboard.
     * @param cr The JCCellRange of cells that are to be copied to the clipboard.
     */
    public ClipboardString(WepsTable table, JCCellRange cr) {
        super(getData(table, cr));
    }
    
    /**
     * Returns a String representation of the cells in the JCTable that fall within the JCCellRange specified.
     * @param table The JCTable containing the cells.
     * @param cr The JCCellRange containing the cells to be copied.
     * @return A String representation of the cells copied from the table.
     */
    static String getData(JCTable table, JCCellRange cr){               
//        String data = "";
        if (cr.end_row == JCTableEnum.MAXINT) {
            cr.end_row = table.getNumRows() - 1;
        }
        if (cr.end_column == JCTableEnum.MAXINT) {
            cr.end_column = table.getNumColumns() - 1;
        }
        StringBuilder sb = new StringBuilder();
        for (int r = cr.start_row; r <= cr.end_row; r++) {
            for (int c = cr.start_column; c < cr.end_column; c++) {             
                Object value = getValue(table, r, c);
                sb.append(value + "\t");
            }
            Object value = getValue(table, r, cr.end_column);
            sb.append(value + "\n");
        }
        return(sb.toString());
    }
    
    /**
     * Return the contents of the cell (r,c) in the JCTable specified.
     * @param table The JCTable to be queried.
     * @param r The row containing the cell to be queried.
     * @param c The column containing the cell to be queried.
     * @return The contents of the cell.
     */
    static Object getValue(JCTable table, int r, int c){
        boolean isWepsTable = table instanceof WepsTable; 
        DataViewModel dvm = table.getDataView();
        Object value = dvm.getObject(r, c);
        if (isWepsTable){
            WepsTable t = (WepsTable) table;
            JCCellDisplayEvent event = new JCCellDisplayEvent(t, r, c, value);
            int flags = WepsTableEnum.PREPARE_adjustments | WepsTableEnum.PREPARE_displayunits | WepsTableEnum.PREPARE_limits;
            t.getDataView().prepareCellDisplay(event, flags);
            value = event.getDisplayData();
        }
        return value;
    }
}
