/*
 * Copyright 2006 Takahiro Nakamura.
 *
 * 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 woolpack.factory;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;

import woolpack.fn.Fn;

/**
 * 委譲先で取得した{@link InputStream}を{@link Reader}に変換する{@link Fn}です。
 * 文字セットが不正な場合は取得した{@link InputStream#close()}を呼び出します。
 * <br/>適用しているデザインパターン：Adapter。
 * 
 * @author nakamura
 * 
 */
public class InputStreamReaderFactory<C> implements Fn<C, Reader> {
	private Fn<? super C, ? extends InputStream> inputStreamFactory;
	private String charset;

	public InputStreamReaderFactory(
			final Fn<? super C, ? extends InputStream> inputStreamFactory,
			final String charset) {
		this.inputStreamFactory = inputStreamFactory;
		this.charset = charset;
	}

	/**
	 * @throws IllegalStateException ({@link IOException})
	 */
	public Reader exec(final C c) {
		final InputStream stream = inputStreamFactory.exec(c);
		if (stream == null) {
			return null;
		} else {
			try {
				if (charset == null || charset.length() == 0) {
					return new BufferedReader(new InputStreamReader(stream));
				} else {
					return new BufferedReader(new InputStreamReader(stream, charset));
				}
			} catch (final IOException e) {
				try {
					stream.close();
				} catch (final IOException e2) {
					// nothing to do.
				}
				throw new IllegalStateException(e);
			}
		}
	}

	public String getCharset() {
		return charset;
	}
	public void setCharset(final String charset) {
		this.charset = charset;
	}
	public Fn<? super C, ? extends InputStream> getInputStreamFactory() {
		return inputStreamFactory;
	}
	public void setInputStreamFactory(final Fn<? super C, ? extends InputStream> inputStreamFactory) {
		this.inputStreamFactory = inputStreamFactory;
	}
}
