/*
 * Copyright 2009-2010 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;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 *
 *
 * @author MORIGUCHI, Yuichiro 2013/03/10
 */
public final class AwkLocation {

	private List<String> path;
	private boolean root;

	/**
	 * 
	 * @param root
	 * @param path
	 */
	public AwkLocation(boolean root, List<String> path) {
		this.root = root;
		this.path = new ArrayList<String>(path);
	}

	/**
	 * 
	 * @param root
	 * @param path
	 */
	public AwkLocation(boolean root, String... path) {
		this.root = root;
		this.path = Arrays.asList(path);
	}

	/**
	 * 
	 * @param name
	 */
	public AwkLocation(String name) {
		this(false, name);
	}

	/**
	 * 
	 * @return
	 */
	public String getName() {
		return path.get(path.size() - 1);
	}

	/**
	 * 
	 * @return
	 */
	public int sizeOfPath() {
		return path.size();
	}

	/**
	 * 
	 * @param x
	 * @return
	 */
	public String getPathOf(int x) {
		return path.get(x);
	}

	/**
	 * 
	 * @return
	 */
	public boolean isRoot() {
		return root;
	}

	/**
	 * 
	 * @return
	 */
	public boolean isSimpleName() {
		return path.size() == 1;
	}

	public int hashCode() {
		int h = path.hashCode();

		return root ? -h : h;
	}

	public boolean equals(Object o) {
		if(o instanceof AwkLocation) {
			return (path.equals(((AwkLocation)o).path) &&
					root == ((AwkLocation)o).root);
		}
		return false;
	}

	public String toString() {
		StringBuffer b = new StringBuffer();
		String d = root ? "." : "";

		for(String s : path) {
			b.append(d).append(s);
			d = ".";
		}
		return b.toString();
	}

}
