package hiro.yoshioka.util.logging;

import java.util.HashMap;
import java.util.Map;

import org.eclipse.swt.custom.StyleRange;
import org.eclipse.swt.custom.StyledText;
import org.eclipse.swt.events.DisposeEvent;
import org.eclipse.swt.events.DisposeListener;
import org.eclipse.swt.graphics.Color;

public abstract class AbsMyLoggingHandler {
	protected StyledText styledText;
	protected Map<String, Color> fColorMap = new HashMap<String, Color>();

	public Map<String, Color> getfColorMap() {
		return fColorMap;
	}

	public void setfColorMap(Map<String, Color> fColorMap) {
		this.fColorMap = fColorMap;
	}

	public abstract void setLevel(String level);

	public abstract String getLevel();

	protected void consoleWrite(StyledTextData data) {
		if (data.fText == null || data.fText.isDisposed()) {
			System.err.println("disposed....... and remove text...........");
			return;
		}
		try {
			int start = data.fText.getText().length();
			data.fText.append(data.fString);

			if (data.fBg != null && data.fFg != null) {
				StyleRange style = new StyleRange(start, data.fString.length(),
						data.fFg, data.fBg);
				data.fText.replaceStyleRanges(start, data.fString.length(),
						new StyleRange[] { style });
			}
			data.fText.setTopIndex(data.fText.getLineCount());
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	class StyledTextRunnable implements Runnable {
		StyledTextData fStyledTextData;

		StyledTextRunnable(StyledTextData data) {
			fStyledTextData = data;
		}

		public void run() {
			consoleWrite(fStyledTextData);
		}
	}

	public void connect(StyledText text) {
		this.styledText = text;
		styledText.addDisposeListener(new DisposeListener() {
			public void widgetDisposed(DisposeEvent e) {
				if (e.widget.equals(AbsMyLoggingHandler.this.styledText)) {
					System.err.println("----------------------------------");
					System.err.println("Already disposed "
							+ AbsMyLoggingHandler.this.styledText);
				}
			}
		});
	}

}
