package jp.hasc.hasctool.ui.views;

import jp.hasc.hasctool.core.runtime.source.AbstractSource;

/**
 * カーソル位置を取得可能なLineReaderSource
 * @author iwasaki
 */
public class CharPosLineReaderSource extends AbstractSource {
	
	private String sourceText_;
	private int posCurrentLineBegins_,posCurrentLineEnds_;

	@Override
	protected void run() throws InterruptedException {
		posCurrentLineBegins_=posCurrentLineEnds_=0;
		int len=sourceText_.length();
		int state=0;
		for(int pos=0;pos<len;++pos) {
			char c=sourceText_.charAt(pos);
			switch(state) {
			case 0: // normal
				if (c=='\r' || c=='\n') {
					posCurrentLineEnds_=pos;
					doOutput();
					posCurrentLineBegins_=pos+1;
					state=(c=='\r')?1:0;
				}
				break;
			case 1: // previous char is '\r'
				if (c=='\r') {
					posCurrentLineEnds_=pos;
					doOutput();
					posCurrentLineBegins_=pos+1;
				}else if (c=='\n') {
					posCurrentLineBegins_=pos+1;
					state=0;
				}
				break;
				
			default: throw new RuntimeException();
			}
		}
		if (posCurrentLineBegins_<len) {
			posCurrentLineEnds_=len;
			doOutput();
		}
	}

	private void doOutput() throws InterruptedException {
		outputMessage(sourceText_.substring(posCurrentLineBegins_, posCurrentLineEnds_));
	}

	public String getSourceText() {
		return sourceText_;
	}

	public void setSourceText(String source) {
		sourceText_ = source;
	}

	public int getPosCurrentLineBegins() {
		return posCurrentLineBegins_;
	}

	public int getPosCurrentLineEnds() {
		return posCurrentLineEnds_;
	}

}
