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

import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

import net.morilib.sh.ShEnvironment;

public class ShSubEnvironment extends AbstractShEnvironment {

	private ShEnvironment env;

	private Map<String, String> map;
	private Map<String, Attributes> attrs;

	public ShSubEnvironment(ShEnvironment env) {
		this.env   = env;
		this.map   = new HashMap<String, String>();
		this.attrs = new HashMap<String, Attributes>();
	}

	public void bind(String name, String value) {
		map.put(name, value);
		setpath();
	}

	public boolean contains(String name) {
		return map.containsKey(name) || env.contains(name);
	}

	public void export(String name) {
		if(!env.contains(name))  map.put(name, "");
	}

	public String find(String name) {
		return map.containsKey(name) ? map.get(name) : env.find(name);
	}

	public ShEnvironment getEnvironment() {
		return this;
	}

	public boolean isReadonly(String name) {
		Attributes a;

		return (a = attrs.get(name)) != null ?
				a.isReadonly() : env.isReadonly(name);
	}

	public void put(String name, String value) {
		map.put(name, value);
	}

	public void setReadonly(String name) {
		if(map.containsKey(name)) {
			attrs.put(name, READONLY);
		} else {
			env.setReadonly(name);
		}
	}

	public Properties toProperties() {
		Properties p = env.toProperties();

		for(Map.Entry<String, String> e : map.entrySet()) {
			p.setProperty(e.getKey(), e.getValue());
		}
		return p;
	}

	public void unbind(String name) {
		if(map.containsKey(name)) {
			map.remove(name);
		} else {
			env.unbind(name);
		}
	}

}
