package usda.weru.util;

import java.awt.*;
import java.util.*;
import java.awt.event.*;
import com.klg.jclass.table.*;
import de.schlichtherle.truezip.file.TFile;
import de.schlichtherle.truezip.file.TFileReader;
import java.io.BufferedReader;
import java.io.IOException;

/**
 *
 * @author maxerdwien
 */
public class ToolTipsTable extends JCTable {
    private static final long serialVersionUID = 1L;

	/**
	 *
	 */
	public boolean debugFlg = false;
	
	java.util.Hashtable<String,String> ht = new java.util.Hashtable<String,String>();

	/**
	 *
	 */
	public ToolTipsTable()
	{
		super();
	}
	
	/**
	 * 
	 * @param tableID 
	 * @param inputFile 
	 */
	public ToolTipsTable(String tableID, TFile inputFile)
	{
		super();

		try {
            try (BufferedReader in = new BufferedReader(new TFileReader(inputFile))) {
                String temp;
                while((temp = in.readLine())!=null) {
                    StringTokenizer st = new StringTokenizer(temp,"=");
                    if (st.countTokens() != 2) continue;
                    String id = st.nextToken().trim();
                    if (!id.startsWith(tableID)) continue;
                    try {
                        id = id.substring(tableID.length() + 1);
                        String value = st.nextToken().trim();
                        if (debugFlg) //System.out.println("U_lTT: " + id + " " + value);
                            ht.put(id, value);
                    } catch (java.util.NoSuchElementException e) {
                        // skip invalid lines - comments or nothing after =
                    }
                }
            }
		} catch (IOException e) {
			//System.err.println("Unable to load tooltips file");
		}
	}

	private String[] labels;
	
	/**
	 * 
	 * @param arr 
	 */
	public void setLabels(String[] arr)
	{
		labels = arr.clone();
	}


	/**
	 * 
	 * @param event 
	 * @return 
	 */
    @Override
	public String getToolTipText(MouseEvent event) {
		JCCellPosition cp = XYToCell(event.getX(), event.getY());
		int column = cp.column;
        //System.out.println("CS_gTTT: " + column);
		if (column < 0) return null;
		try {
			String rtn = ht.get(labels[column]);
			return "<html>" + ((rtn == null) ? "no help" : rtn) + "</html>";
		} catch (java.lang.ArrayIndexOutOfBoundsException e) {
			return "<html>" + "out of bounds " + column + "</html>";
		}
	}

    /**
     * Override Swing's poor label position choice.  The
     * new behaviour is very simple: show the label at the
     * current location of the mouse.
	 * @param event
	 * @return 
    */
    @Override
	public Point getToolTipLocation(MouseEvent event) {
		return new Point(event.getX()+10, event.getY());
	}
}

