package project.web.generic;

import java.io.IOException;

import javax.servlet.http.HttpServletResponse;

import org.apache.logging.log4j.LogManager;

import core.exception.LogicalException;
import net.arnx.jsonic.JSON;
import online.context.RequestParameter;
import online.context.check.InputCheck;
import online.model.UniModel;
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 OptionAction implements RestAction {

	/**
	 * 取得処理
	 *
	 * @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 QueryService ql = InstanceFactory.create(QueryService.class, model);
		if (!ql.search()) {
			throw new LogicalException(HttpServletResponse.SC_NOT_FOUND);
		}

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

			final UniModel um = ql.getResultModel();
			JSON.encode(new String[][]{
						um.getStringArray(getOptionLabel(model)),
						um.getStringArray(getOptionValue(model))},
						response.getWriter());

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

		return null;
	}

	/**
	 * ラベル項目名取得
	 * @param model 汎用モデル
	 * @return ラベル項目名
	 */
	private String getOptionLabel(final UniForm model) {
		final String label = model.getString("OptionLabelName");
		return label.isEmpty() ? "Label" : label;
	}

	/**
	 * 値項目名取得
	 * @param model 汎用モデル
	 * @return 値項目名
	 */
	private String getOptionValue(final UniForm model) {
		final String value = model.getString("OptionValueName");
		return value.isEmpty() ? "Value" : value;
	}

	/**
	 * 入力チェック
	 *
	 * @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();
	}
}
