package project.web.generic;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.logging.log4j.LogManager;

import online.context.RequestParameter;
import online.context.check.InputCheck;
import online.struts.action.RestAction;
import online.struts.action.UniForm;
import online.struts.mapping.RequestMapping;
import project.check.range.LengthRangeCheck;
import project.svc.generic.CsvService;
import project.web.DownloadAction;
import project.web.InstanceFactory;

/**
 * 汎用Csv照会
 *
 * @author Tadashi Nakayama
 * @version 1.0.0
 */
public final class CsvFileAction implements RestAction, DownloadAction {

	/**
	 * 主処理
	 *
	 * @param mapping ActionMappingオブジェクト
	 * @param uf 汎用フォーム
	 * @param request HttpServletRequestオブジェクト
	 * @param response HttpServletResponseオブジェクト
	 * @return 処理結果
	 */
	public String get(final UniForm uf, final HttpServletResponse response,
			final HttpServletRequest request, final RequestMapping mapping) {
		// 入力チェック
		checkInput(uf);

		try {
			//DB情報取得
			final CsvService jdq = InstanceFactory.create(CsvService.class, uf);
			jdq.showTitle(needsTitle(uf));
			jdq.setOutputStream(response.getOutputStream());

			// httpヘッダ出力
			putHttpHeader(jdq, mapping, request, response);

			jdq.search();

			response.flushBuffer();

		} catch (final IOException ex) {
			LogManager.getLogger().info(ex.getMessage());
		}

		return null;
	}

	/**
	 * 入力チェック
	 *
	 * @param model 汎用モデル
	 */
	private void checkInput(final UniForm model) {
		final InputCheck ic = InstanceFactory.create(InputCheck.class, model);
		final RequestParameter pm = model.getActionParameter().getParameter();
		pm.keySet().stream().forEach(k -> ic.add(k, new LengthRangeCheck(0, 1024)));
		ic.populate();
	}

	/**
	 * httpヘッダ設定
	 * @param cs CsvService
	 * @param mapping マッピング
	 * @param request リクエスト
	 * @param response レスポンス
	 */
	private void putHttpHeader(final CsvService cs, final RequestMapping mapping,
			final HttpServletRequest request, final HttpServletResponse response) {
		final String name = mapping.getPath().substring("/".length()) + ".csv";
		setHttpHeader(name, name, request, response);
		response.setContentType(response.getContentType() + "; "
				+ toCsvHeaderQuery(cs.isTitled()) + "; charset=" + cs.getCharset());
	}
}
