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

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

import net.morilib.sh.ShEnvironment;

public class ShUnixEnvironment extends AbstractShEnvironment {

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

	ShUnixEnvironment() {
		this.attrs = new HashMap<String, Attributes>();
		try {
			map = new HashMap<String, String>(System.getenv());
			setpath();
		} catch(SecurityException e) {
			map = new HashMap<String, String>();
		}
	}

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

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

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

	public ShEnvironment getEnvironment() {
		return null;
	}

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

	public Properties toProperties() {
		Properties r = new Properties();

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

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

	public void unbind(String name) {
		map.remove(name);
	}

	public boolean isReadonly(String name) {
		Attributes a;

		return (a = attrs.get(name)) != null && a.isReadonly();
	}

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

}
