/*
 * 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.sed;

public class SedSubstituteFlags {

	//
	boolean global = false, print = false, caseInsensitive = false;
	boolean allmatch = false;
	String desc, fileToWrite = null;
	int number = -1;

	void init(String s) {
		StringBuffer b = new StringBuffer();
		int c;

		for(int i = 0; i < s.length(); i++) {
			if((c = s.charAt(i)) == 'g') {
				global = true;
			} else if(c >= '0' && c <= '9') {
				for(; i < s.length(); i++) {
					if((c = s.charAt(i)) < '0' || c > '9')  break;
					b.append((char)c);
				}
				number = Integer.parseInt(b.toString());
			} else if(c == 'p') {
				print = true;
			} else if(c == 'w') {
				fileToWrite = s.substring(i + 1);
				return;
			} else if(c == 'i') {
				caseInsensitive = true;
			} else if(c == 'm') {
				allmatch = true;
			} else {
				// an unknown flag
			}
		}
	}

	public SedSubstituteFlags(String flags) {
		desc = flags;
		init(flags);
	}

	public boolean isGlobal() {
		return global;
	}

	public boolean isPrint() {
		return print;
	}

	public boolean isCaseInsensitive() {
		return caseInsensitive;
	}

	public String getFileToWrite() {
		return fileToWrite;
	}

	public boolean isAllmatch() {
		return allmatch;
	}

	public int getNumber() {
		return number;
	}

	@Override
	public int hashCode() {
		int r = 17;

		r = (r * 37) + (global ? 1 : 0);
		r = (r * 37) + (print ? 1 : 0);
		r = (r * 37) + (caseInsensitive ? 1 : 0);
		r = (r * 37) + (fileToWrite == null ?
				0 : fileToWrite.hashCode());
		r = (r * 37) + (number < 0 ? -1 : number);
		return r;
	}

	private static boolean eq(Object a, Object b) {
		return a == null ? b == null : a.equals(b);
	}

	@Override
	public boolean equals(Object o) {
		SedSubstituteFlags f;

		if(o instanceof SedSubstituteFlags) {
			f = (SedSubstituteFlags)o;
			return (global == f.global &&
					print == f.print &&
					caseInsensitive == f.caseInsensitive &&
					eq(fileToWrite, f.fileToWrite) &&
					number < 0 ? f.number < 0 : number == f.number);
		}
		return false;
	}

	@Override
	public String toString() {
		return desc;
	}

}
