package project.web.generic;

import java.io.IOException;

import javax.servlet.http.HttpServletResponse;

import org.apache.logging.log4j.LogManager;

import com.fasterxml.jackson.databind.ObjectMapper;

import core.exception.LogicalException;
import online.context.check.InputCheck;
import online.struts.action.RestAction;
import online.struts.action.UniForm;
import project.check.range.LengthRangeCheck;
import project.svc.generic.QueryService;
import project.web.InstanceFactory;

/**
 * 選択候補アクション
 *
 * @author Tadashi Nakayama
 * @version 1.0.0
 */
public final class SuggestAction implements RestAction {

	/** クエリ */
	private String query = null;

	/**
	 * クエリ設定
	 *
	 * @param qry クエリファイル
	 */
	public void setQueryFile(final String qry) {
		this.query = qry;
	}

	/**
	 * 取得処理
	 *
	 * @param model 汎用データモデル
	 * @param response レスポンス
	 * @return 処理結果
	 */
	public String get(final UniForm model, final HttpServletResponse response) {
		if (!model.hasQueryString()) {
			throw new LogicalException(HttpServletResponse.SC_BAD_REQUEST);
		}

		// 入力チェック
		checkInput(model);

		//DB情報取得
		final var ql = InstanceFactory.create(QueryService.class, model);
		ql.setQueryFile(this.query);
		if (!ql.search()) {
			throw new LogicalException(HttpServletResponse.SC_NOT_FOUND);
		}

		try {
			response.setContentType("application/json; charset=UTF-8");

			final ObjectMapper mapper = new ObjectMapper();
			mapper.writeValue(response.getWriter(), ql.getResultModel().getStringArray("Value"));

			response.flushBuffer();
		} 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, 24)));
		ic.populate();
	}
}
