package hiro.yoshioka.sql.util;

import hiro.yoshioka.sdh.ResultSetDataHolder;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.eclipse.swt.program.Program;

public class LinkHrefInfo extends LinkInfo {
	boolean doPopUp;
	public final int[] bind;
	public String href;
	static final Pattern P = Pattern.compile("([$]\\d+)");

	public LinkHrefInfo(int colIdx, String message, int[] ibind, boolean doPopUp) {
		super(colIdx);
		this.bind = ibind;
		this.href = message.trim();
		this.doPopUp = doPopUp;
	}

	public void normalIE(ResultSetDataHolder rdh, int row) {
		try {
			if (bind.length > 0) {
				StringBuffer buf = new StringBuffer();
				Matcher m = P.matcher(href);
				fLogger.trace("bind.length=" + bind.length);
				for (int i = 0; m.find() && i < bind.length; i++) {
					String str = rdh.getRow(row)[bind[i++]];
					m.appendReplacement(buf, str);
					fLogger.trace("str [" + str + "]");
				}
				m.appendTail(buf);
				fLogger.trace("url [" + buf + "]");
				Program.launch(buf.toString());
				return;
			}
		} catch (RuntimeException e) {
			fLogger.error(e);
		}
		Program.launch(href);

	}

	public void execute(ResultSetDataHolder rdh, int row) {
		normalIE(rdh, row);
	}

	@Override
	public String toString() {
		return super.toString() + " BIND:" + bind + " HREF=" + href + " POPUP="
				+ doPopUp;
	}
}
