package core.config;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.MissingResourceException;
import java.util.Properties;
import java.util.ResourceBundle;

import org.apache.logging.log4j.LogManager;


/**
 * プロパティ読込
 *
 * @author Tadashi Nakayama
 */
public class EncodingProperties extends Properties {
	/** serialVersionUID */
	private static final long serialVersionUID = 1965903306454240284L;

	/** エンコードキー */
	private static final String KEY_ENCODING = "This.Encoding";

	/** エンコード */
	private final String encoding;

	/**
	 * コンストラクタ
	 *
	 * @param val エンコード
	 */
	public EncodingProperties(final Charset val) {
		if (val != null) {
			this.encoding = val.name();
		} else {
			this.encoding = StandardCharsets.UTF_8.name();
		}
	}

	/**
	 * コンストラクタ
	 *
	 * @param resource リソース
	 */
	public EncodingProperties(final ResourceBundle resource) {
		// エンコード取得
		String ret = StandardCharsets.UTF_8.name();
		try {
			final String enc = resource.getString(KEY_ENCODING).trim();
			if (!enc.isEmpty()) {
				ret = enc;
			}
		} catch (final MissingResourceException ex) {
			LogManager.getLogger().info(ex.getMessage());
		}
		this.encoding = ret;
	}

	/**
	 * @see java.util.Properties#load(java.io.InputStream)
	 */
	@Override
	public synchronized void load(final InputStream inStream) throws IOException {
		try (InputStreamReader isr = new InputStreamReader(inStream, this.encoding)) {
			try (BufferedReader br = new BufferedReader(isr)) {
				for (String buf = br.readLine(); buf != null; buf = br.readLine()) {
					final String buff = buf.trim();
					if (!buff.isEmpty() && !buff.startsWith("#")) {
						final int loc = buff.indexOf('=');
						if (0 < loc) {
							setProperty(buff.substring(0, loc), buff.substring(loc + "=".length()));
						}
					}
				}
			}
		}
	}

	/**
	 * @see java.util.Hashtable#equals(java.lang.Object)
	 */
	@Override
	public synchronized boolean equals(final Object o) {
		return o != null && super.equals(o);
	}

	/**
	 * @see java.util.Hashtable#hashCode()
	 */
	@Override
	public synchronized int hashCode() {
		return this.isEmpty() ? 0 : super.hashCode();
	}
}
