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 core.file.ZippedLineOutputStream;
import core.util.MojiUtil;
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 CsvZipAction 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 var jdq = InstanceFactory.create(CsvService.class, uf);
			jdq.showTitle(needsTitle(uf));

			try (var zos = getOutputStream(response, mapping)) {
				jdq.setOutputStream(zos);

				// httpヘッダ出力
				final var name = mapping.getPath().substring("/".length()) + ".zip";
				setHttpHeader(name, name, request, response);

				jdq.search();

				zos.finish();
			}

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

		return null;
	}

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

	/**
	 * OutputStream取得
	 * @param response レスポンス
	 * @param mapping マッピング
	 * @return OutputStream
	 * @throws IOException IO例外
	 */
	private ZippedLineOutputStream getOutputStream(final HttpServletResponse response,
			final RequestMapping mapping) throws IOException {
		final var zos = new ZippedLineOutputStream(
				response.getOutputStream(), MojiUtil.CHARSET_W31J);
		zos.setEntryName(mapping.getPath().substring("/".length()) + ".csv");
		return zos;
	}
}
