/*
 * Aipo is a groupware program developed by Aimluck,Inc.
 * http://aipostyle.com/
 * 
 * Copyright(C) 2011 avanza Co.,Ltd. All rights reserved.
 * http://www.avnz.co.jp/
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package com.aimluck.eip.account;

import org.apache.cayenne.exp.Expression;
import org.apache.cayenne.exp.ExpressionFactory;
import org.apache.jetspeed.services.logging.JetspeedLogFactoryService;
import org.apache.jetspeed.services.logging.JetspeedLogger;
import org.apache.turbine.util.RunData;
import org.apache.velocity.context.Context;

import com.aimluck.commons.field.ALStringField;
import com.aimluck.commons.utils.ALStringUtil;
import com.aimluck.eip.cayenne.om.account.EipMUserPosition;
import com.aimluck.eip.cayenne.om.portlet.EipMMailAccount;
import com.aimluck.eip.cayenne.om.security.TurbineGroup;
import com.aimluck.eip.cayenne.om.security.TurbineUser;
import com.aimluck.eip.cayenne.om.security.TurbineUserGroupRole;
import com.aimluck.eip.common.ALDBErrorException;
import com.aimluck.eip.common.ALEipConstants;
import com.aimluck.eip.common.ALPageNotFoundException;
import com.aimluck.eip.modules.actions.common.ALAction;
import com.aimluck.eip.orm.Database;
import com.aimluck.eip.orm.query.ResultList;
import com.aimluck.eip.orm.query.SelectQuery;
import com.aimluck.eip.util.ALEipUtils;

/**
 * ユーザーアカウントの検索データを管理するためのクラスです。 <br />
 * 
 */
public class AccountUserWordSelectData extends AccountUserSelectData {

  /** logger */
  private static final JetspeedLogger logger =
    JetspeedLogFactoryService.getLogger(AccountUserWordSelectData.class
      .getName());

  /** 検索ワード */
  protected ALStringField searchWord;

  /**
   * 初期化します。
   * 
   */
  @Override
  public void init(ALAction action, RunData rundata, Context context)
      throws ALPageNotFoundException, ALDBErrorException {

    super.init(action, rundata, context);

    // ページャからきた場合に検索ワードをセッションへ格納する
    if (!rundata.getParameters().containsKey(ALEipConstants.LIST_START)
      && !rundata.getParameters().containsKey(ALEipConstants.LIST_SORT)
      && !rundata.getParameters().containsKey("reload")) {
      ALEipUtils.setTemp(rundata, context, "UserAccountWord", rundata
        .getParameters()
        .getString("sword"));
    }

    // 検索ワードの設定
    searchWord = new ALStringField();
    searchWord.setTrim(true);
    searchWord
      .setValue(ALEipUtils.getTemp(rundata, context, "UserAccountWord"));
  }

  /**
   * 自分がオーナーのアドレスを取得
   * 
   * @param rundata
   * @param context
   * @return
   */
  @Override
  protected ResultList<TurbineUser> selectList(RunData rundata, Context context) {
    ResultList<TurbineUser> list;
    try {
      SelectQuery<TurbineUser> query = getSelectQuery(rundata, context);
      buildSelectQueryForListView(query);
      query.orderAscending(TurbineUser.DISPLAY_NAME_PROPERTY);
      query.orderAscending(TurbineUser.EIP_MUSER_POSITION_PROPERTY
        + "."
        + EipMUserPosition.POSITION_PROPERTY);
      list = query.getResultList();
    } catch (Exception ex) {
      logger.error("ユーザー情報の検索に失敗しました。", ex);
      return null;
    }
    return list;
  }

  /**
   * 
   * @param rundata
   * @param context
   * @return
   */
  private SelectQuery<TurbineUser> getSelectQuery(RunData rundata,
      Context context) {
    SelectQuery<TurbineUser> query = null;
    String word = searchWord.getValue();
    String transWord =
      ALStringUtil.convertHiragana2Katakana(ALStringUtil
        .convertH2ZKana(searchWord.getValue()));

    query = Database.query(TurbineUser.class);

    Expression exp00 =
      ExpressionFactory.matchExp(TurbineUser.DISABLED_PROPERTY, "F");

    Expression exp01 =
      ExpressionFactory.matchExp(TurbineUser.DISABLED_PROPERTY, "N");

    Expression exp02 =
      ExpressionFactory.noMatchDbExp(TurbineUser.USER_ID_PK_COLUMN, Integer
        .valueOf(1));
    Expression exp03 =
      ExpressionFactory.noMatchDbExp(TurbineUser.USER_ID_PK_COLUMN, Integer
        .valueOf(2));
    Expression exp04 =
      ExpressionFactory.noMatchDbExp(TurbineUser.USER_ID_PK_COLUMN, Integer
        .valueOf(3));

    query.setQualifier(exp00.orExp(exp01).andExp(
      exp02.andExp(exp03).andExp(exp04)));

    Expression exp09 =
      ExpressionFactory.likeExp(TurbineUser.DISPLAY_NAME_PROPERTY, "%"
        + word
        + "%");
    Expression exp10 =
      ExpressionFactory.likeExp(TurbineUser.LOGIN_NAME_PROPERTY, "%"
        + word
        + "%");
    Expression exp11 =
      ExpressionFactory.likeExp(TurbineUser.FIRST_NAME_PROPERTY, "%"
        + word
        + "%");
    Expression exp12 =
      ExpressionFactory.likeExp(TurbineUser.LAST_NAME_PROPERTY, "%"
        + word
        + "%");
    Expression exp13 =
      ExpressionFactory.likeExp(TurbineUser.FIRST_NAME_KANA_PROPERTY, "%"
        + word
        + "%");
    Expression exp14 =
      ExpressionFactory.likeExp(TurbineUser.LAST_NAME_KANA_PROPERTY, "%"
        + word
        + "%");
    Expression exp15 =
      ExpressionFactory.likeExp(TurbineUser.EMAIL_PROPERTY, "%" + word + "%");
    Expression exp16 =
      ExpressionFactory.likeExp(TurbineUser.TURBINE_USER_GROUP_ROLE_PROPERTY
        + "."
        + TurbineUserGroupRole.TURBINE_GROUP_PROPERTY
        + "."
        + TurbineGroup.GROUP_ALIAS_NAME_PROPERTY, "%" + word + "%");

    Expression exp17 =
      ExpressionFactory.likeExp(TurbineUser.EIP_MMAILACCOUNT_PROPERTY
        + "."
        + EipMMailAccount.MAIL_ADDRESS_PROPERTY, "%" + word + "%");

    Expression exp30 =
      ExpressionFactory.likeExp(TurbineUser.DISPLAY_NAME_PROPERTY, "%"
        + transWord
        + "%");
    Expression exp31 =
      ExpressionFactory.likeExp(TurbineUser.FIRST_NAME_PROPERTY, "%"
        + transWord
        + "%");
    Expression exp32 =
      ExpressionFactory.likeExp(TurbineUser.LAST_NAME_PROPERTY, "%"
        + transWord
        + "%");
    Expression exp33 =
      ExpressionFactory.likeExp(TurbineUser.FIRST_NAME_KANA_PROPERTY, "%"
        + transWord
        + "%");
    Expression exp34 =
      ExpressionFactory.likeExp(TurbineUser.LAST_NAME_KANA_PROPERTY, "%"
        + transWord
        + "%");
    Expression exp35 =
      ExpressionFactory.likeExp(TurbineUser.TURBINE_USER_GROUP_ROLE_PROPERTY
        + "."
        + TurbineUserGroupRole.TURBINE_GROUP_PROPERTY
        + "."
        + TurbineGroup.GROUP_ALIAS_NAME_PROPERTY, "%" + transWord + "%");

    if (word != null && !"".equals(word)) {
      query.andQualifier(exp10
        .orExp(exp09)
        .orExp(exp11)
        .orExp(exp12)
        .orExp(exp13)
        .orExp(exp14)
        .orExp(exp15)
        .orExp(exp16)
        .orExp(exp17)
        .orExp(exp30)
        .orExp(exp31)
        .orExp(exp32)
        .orExp(exp33)
        .orExp(exp34)
        .orExp(exp35));
    }
    query.distinct();

    return query;
  }

  /**
   * 検索ワードを取得します。
   * 
   * @return
   */
  public ALStringField getSearchWord() {
    return searchWord;
  }

}
