package jp.kirikiri.tjs2;

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

public class RegExpNI extends NativeInstanceObject {

	private static final int
		MEMBERENSURE		= 0x00000200; // create a member if not exists

	public Pattern RegEx;
	public int mFlags;
	public int mStart;
	public Variant mArray;
	public int mIndex;
	public String mInput;
	public int mLastIndex;
	public String mLastMatch;
	public String mLastParen;
	public String mLeftContext;
	public String mRightContext;
	public Matcher mMatch;

	private static final int globalsearch = (1<<31);

	public static int regExpFlagToValue( char ch, int prev ) {
		// converts flag letter to internal flag value.
		// this returns modified prev.
		// when ch is '\0', returns default flag value and prev is ignored.

		if( ch == 0 ) {
			return 0;
		}

		switch(ch) {
		case 'g': // global search
			prev|=globalsearch; return prev;
		case 'i': // ignore case
			prev|=Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE; return prev;
		case 'l': // use localized collation
			//prev &= ~regbase::nocollate; return prev; 無視
			return prev;
		default:
			return prev;
		}
	}
	public static int getRegExpFlagsFromString( final String string ) {
		// returns a flag value represented by string
		int flag = regExpFlagToValue( (char)0, 0);
		final int count = string.length();
		int i = 0;
		while( i < count && string.charAt(i) != '/' ) {
			flag = regExpFlagToValue( string.charAt(i), flag);
			i++;
		}
		return flag;
	}
	public RegExpNI() {
		mFlags = regExpFlagToValue((char) 0, 0);
		mStart = 0;
		mIndex =0;
		mLastIndex = 0;
		mArray = new Variant();
	}
	public void split( Holder<Dispatch2> array, String target, boolean purgeempty) throws VariantException, TJSException {
		if( array.mValue == null ) {
			array.mValue = TJS.createArrayObject();
		}
		if( RegEx != null ) {
			int limit = 0;
			if( purgeempty == false ) limit = -1;
			String strs[] = RegEx.split(target,limit);
			final int count = strs.length;
			for( int i = 0; i < count; i++ ) {
				Variant val = new Variant(strs[i]);
				array.mValue.propSetByNum( MEMBERENSURE, i, val, array.mValue );
			}
		}
	}
}
