/*
 * Copyright 2013 Yuichiro Moriguchi
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package net.morilib.awk.nano.value;

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

import net.morilib.awk.nano.AwkRuntimeException;
import net.morilib.awk.nano.namespace.AwkNamespace;

/**
 * awkium正規表現のクラスです。
 * 
 * @author MORIGUCHI, Yuichiro 2013/03
 */
public class AwkRegex extends AwkValue {

	private Pattern regex;

	private AwkRegex(String regex) {
		this.regex = Pattern.compile(regex);
	}

	/**
	 * 正規表現を取得します。
	 * 
	 * @param regex 正規表現
	 * @return awkium正規表現
	 */
	public static AwkRegex valueOf(String regex) {
		try {
			return new AwkRegex(regex);
		} catch(PatternSyntaxException e) {
			throw new AwkRuntimeException("invalid regex: " + regex);
		}
	}

	public boolean isFloat() {
		return false;
	}

	public boolean isInteger() {
		return false;
	}

	public boolean isReal() {
		return false;
	}

	public boolean isFloatValue() {
		return false;
	}

	public boolean isIntegerValue() {
		return false;
	}

	public boolean isRealValue() {
		return false;
	}

	public boolean isNegativeValue() {
		return false;
	}

	public boolean isPositiveValue() {
		return false;
	}

	public boolean isZeroValue() {
		return false;
	}

	public boolean isString() {
		return false;
	}

	public boolean isRegex() {
		return true;
	}

	public boolean isFunction() {
		return false;
	}

	@Override
	public boolean isEmpty() {
		return false;
	}

	public boolean toBoolean(AwkNamespace ns) {
		Matcher m = regex.matcher(ns.referField(0).toString());

		return m.find();
	}

	public Pattern toRegex(AwkNamespace ns) {
		String s;

		if(ns.isIgnoreCase()) {
			s = regex.pattern();
			return Pattern.compile(s, Pattern.CASE_INSENSITIVE);
		} else {
			return regex;
		}
	}

	/* (non-Javadoc)
	 * @see net.morilib.awk.value.AwkValue#toObject()
	 */
	public Object toObject() {
		return regex;
	}

	public int compareTo(AwkValue o, AwkNamespace ns) {
		if(o instanceof AwkUndefined) {
			return 1;
		} else if(ns.isIgnoreCase()) {
			return toString(ns).compareToIgnoreCase(o.toString(ns));
		} else {
			return toString(ns).compareTo(o.toString(ns));
		}
	}

	@Override
	public String toString(AwkNamespace ns) {
		return regex.pattern();
	}

}
