/*
 * Aipo is a groupware program developed by Aimluck,Inc.
 * Copyright (C) 2004-2011 Aimluck,Inc.
 * http://www.aipo.com
 *
 * 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.addressbook;

import java.util.ArrayList;
import java.util.List;
import java.util.jar.Attributes;

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.utils.ALStringUtil;
import com.aimluck.eip.addressbook.util.AddressBookUtils;
import com.aimluck.eip.cayenne.om.portlet.EipMAddressGroup;
import com.aimluck.eip.cayenne.om.portlet.EipMAddressbook;
import com.aimluck.eip.cayenne.om.portlet.EipTAddressbookGroupMap;
import com.aimluck.eip.common.ALDBErrorException;
import com.aimluck.eip.common.ALEipConstants;
import com.aimluck.eip.common.ALEipGroup;
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.services.accessctl.ALAccessControlConstants;
import com.aimluck.eip.util.ALCommonUtils;
import com.aimluck.eip.util.ALEipUtils;

/**
 * アドレス帳での検索BOX用データです。(社外アドレス検索用)
 * 
 */
public class AddressBookWordSelectData extends
    AbstractAddressBookWordSelectData<EipMAddressbook, EipMAddressbook> {

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

  /** フィルタに利用するグループリスト */
  private List<AddressBookGroupResultData> groupList;

  /** マイグループリスト */
  private final List<ALEipGroup> myGroupList = null;

  // add start
  /** ログインユーザーID */
  private int loginuserid;

  // add end

  /**
   * 初期処理
   * 
   * @param action
   *            アクションクラス
   * @param rundata
   *            JetSpeedランデータ
   * @param context
   *            JetSpeedコンテキスト
   * @throws ALPageNotFoundException
   * @throws ALDBErrorException
   */
  @Override
  public void init(ALAction action, RunData rundata, Context context)
      throws ALPageNotFoundException, ALDBErrorException {
    // add start
    // 個人アドレス帳対応
    String sort = ALEipUtils.getTemp(rundata, context, LIST_SORT_STR);
    if (sort == null || sort.equals("")) {
      ALEipUtils.setTemp(rundata, context, LIST_SORT_STR, "company_name");
    }
    // add end
    super.init(action, rundata, context);
  }

  /**
   * 個人アドレスの一覧取得処理
   * 
   * @param rundata
   *            JetSpeedランデータ
   * @param context
   *            JetSpeedコンテキスト
   * @return 個人アドレスリスト
   */
  @Override
  protected ResultList<EipMAddressbook> selectList(RunData rundata,
      Context context) {
    // ResultList<EipMAddressbook> list;

    try {
      SelectQuery<EipMAddressbook> query = getSelectQuery(rundata, context);
      // buildSelectQueryForListView(query);
      buildSelectQueryForListViewSort(query, rundata, context);
      // list = query.getResultList();
      List<EipMAddressbook> list = query.getResultList();
      int totalSize = list.size();
      return new ResultList<EipMAddressbook>(
        buildPaginatedList(list),
        current_page,
        getRowsNum(),
        totalSize);
    } catch (Exception ex) {
      // change start
      // logger.error("Exception", ex);
      String msg =
        "個人アドレスの一覧取得に失敗しました。[" + ALEipUtils.getUserLoginName(loginuserid) + "]";
      logger.error(msg, ex);
      // change end
      return null;
    }
    // return list;
  }

  /**
   * ※未使用
   */
  @Override
  protected EipMAddressbook selectDetail(RunData rundata, Context context) {
    return null;
  }

  /**
   * ResultData に値を格納して返します。（一覧データ） <BR>
   * 
   * @param obj
   *            DBから取得し個人アドレス情報
   * @return 画面表示用データ
   * @see com.aimluck.eip.common.ALAbstractSelectData#getListData(java.lang.Object)
   */
  @Override
  protected Object getResultData(EipMAddressbook obj) {
    try {
      AddressBookResultData rd = new AddressBookResultData();

      EipMAddressbook record = obj;
      rd.initField();
      rd.setAddressId(record.getAddressId().intValue());

      // change start
      // rd.setName(new StringBuffer()
      // .append(record.getLastName())
      // .append(" ")
      // .append(record.getFirstName())
      // .toString());
      // rd.setNameKana(new StringBuffer()
      // .append(record.getLastNameKana())
      // .append(' ')
      // .append(record.getFirstNameKana())
      // .toString());
      rd.setName(AddressBookUtils.makeFullName(record.getLastName(), record
        .getFirstName()));
      rd.setNameKana(AddressBookUtils.makeFullName(
        record.getLastNameKana(),
        record.getFirstNameKana()));
      // change end

      // change by motegi start 個人アドレス帳
      // EipMAddressbookCompany company = record.getEipMAddressbookCompany();
      // // : 「未分類」の会社情報ではない場合
      // if
      // (!AddressBookUtils.EMPTY_COMPANY_NAME.equals(company.getCompanyName()))
      // {
      // rd.setCompanyId(company.getCompanyId().toString());
      // rd.setCompanyName(ALCommonUtils.compressString(
      // company.getCompanyName(),
      // getStrLength()));
      // rd.setPostName(ALCommonUtils.compressString(
      // company.getPostName(),
      // getStrLength()));
      // }
      EipMAddressGroup company =
        AddressBookUtils.getEipMAddressGroup(record.getAddressId());
      if (company != null) {
        rd.setCompanyId(company.getGroupId().toString());
        rd.setCompanyName(ALCommonUtils.compressString(
          company.getGroupName(),
          getStrLength()));
      }
      // change end

      rd.setPositionName(ALCommonUtils.compressString(
        record.getPositionName(),
        getStrLength()));
      rd.setEmail(ALCommonUtils.compressString(
        record.getEmail(),
        getStrLength()));
      rd.setTelephone(record.getTelephone());
      rd.setCellularPhone(record.getCellularPhone());
      rd.setCellularMail(record.getCellularMail());
      rd.setPublicFlag(record.getPublicFlag());

      // add by motegi start 個人アドレス帳対応
      rd.setFaxNumber(record.getFaxNumber());
      // add end

      return rd;
    } catch (Exception ex) {
      // change start
      // logger.error("Exception", ex);
      String msg =
        "個人アドレスの検索処理に失敗しました。[" + ALEipUtils.getUserLoginName(loginuserid) + "]";
      logger.error(msg, ex);
      // change end
      return null;
    }
  }

  /**
   * ※未使用
   */
  @Override
  protected Object getResultDataDetail(EipMAddressbook obj) {
    return null;
  }

  /**
   * ソート用カラムマップ取得
   * 
   * @return ソート用カラムマップ
   */
  @Override
  protected Attributes getColumnMap() {
    Attributes map = new Attributes();
    map.putValue("group", EipMAddressbook.EIP_TADDRESSBOOK_GROUP_MAP_PROPERTY
      + "."
      + EipTAddressbookGroupMap.EIP_TADDRESS_GROUP_PROPERTY
      + "."
      + EipMAddressGroup.GROUP_ID_PK_COLUMN);
    // change start
    map.putValue("name_kana", EipMAddressbook.LAST_NAME_KANA_PROPERTY);
    // map.putValue("name_kana", EipMAddressbook.LAST_NAME_PROPERTY);
    // change end
    // change by motegi start 個人アドレス帳対応
    // map.putValue(
    // "company_name_kana",
    // EipMAddressbook.EIP_MADDRESSBOOK_COMPANY_PROPERTY
    // + "."
    // + EipMAddressbookCompany.COMPANY_NAME_KANA_PROPERTY);
    map.putValue(
      "company_name",
      EipMAddressbook.EIP_TADDRESSBOOK_GROUP_MAP_PROPERTY
        + "."
        + EipTAddressbookGroupMap.EIP_TADDRESS_GROUP_PROPERTY
        + "."
        + EipMAddressGroup.GROUP_NAME_PROPERTY);
    // change end
    // add start
    // map.putValue("first_name_kana",
    // EipMAddressbook.FIRST_NAME_KANA_PROPERTY);

    // add end
    return map;
  }

  /**
   * 検索条件を設定した SelectQuery を返します。 <BR>
   * 
   * @param rundata
   *            JetSpeedランデータ
   * @param context
   *            JetSpeedコンテキスト
   * @return SQLオブジェクト
   */
  private SelectQuery<EipMAddressbook> getSelectQuery(RunData rundata,
      Context context) {
    SelectQuery<EipMAddressbook> query = null;
    String word = searchWord.getValue();
    String transWord =
      ALStringUtil.convertHiragana2Katakana(ALStringUtil
        .convertH2ZKana(searchWord.getValue()));

    query = Database.query(EipMAddressbook.class);

    // remove start
    // Expression exp01 =
    // ExpressionFactory.matchExp(EipMAddressbook.PUBLIC_FLAG_PROPERTY, "T");
    // remove end
    Expression exp02 =
      ExpressionFactory.matchExp(EipMAddressbook.OWNER_ID_PROPERTY, ALEipUtils
        .getUserId(rundata));
    // remove start
    // Expression exp03 =
    // ExpressionFactory.matchExp(EipMAddressbook.PUBLIC_FLAG_PROPERTY, "F");
    // remove end
    // change start
    // query.setQualifier(exp01.orExp(exp02.andExp(exp03)));
    query.setQualifier(exp02);
    // change end

    Expression exp11 =
      ExpressionFactory.likeExp(EipMAddressbook.FIRST_NAME_PROPERTY, "%"
        + word
        + "%");
    Expression exp12 =
      ExpressionFactory.likeExp(EipMAddressbook.LAST_NAME_PROPERTY, "%"
        + word
        + "%");
    Expression exp13 =
      ExpressionFactory.likeExp(EipMAddressbook.FIRST_NAME_KANA_PROPERTY, "%"
        + word
        + "%");
    Expression exp14 =
      ExpressionFactory.likeExp(EipMAddressbook.LAST_NAME_KANA_PROPERTY, "%"
        + word
        + "%");
    Expression exp15 =
      ExpressionFactory.likeExp(EipMAddressbook.EMAIL_PROPERTY, "%"
        + word
        + "%");
    Expression exp16 =
      ExpressionFactory.likeExp(EipMAddressbook.TELEPHONE_PROPERTY, "%"
        + word
        + "%");
    Expression exp17 =
      ExpressionFactory.likeExp(EipMAddressbook.CELLULAR_PHONE_PROPERTY, "%"
        + word
        + "%");
    // add start
    Expression exp18 =
      ExpressionFactory.likeExp(EipMAddressbook.FAX_NUMBER_PROPERTY, "%"
        + word
        + "%");
    // add end

    // change start
    // Expression exp21 =
    // ExpressionFactory.likeExp(
    // EipMAddressbook.EIP_MADDRESSBOOK_COMPANY_PROPERTY
    // + "."
    // + EipMAddressbookCompany.COMPANY_NAME_PROPERTY,
    // "%" + word + "%");
    // Expression exp22 =
    // ExpressionFactory.likeExp(
    // EipMAddressbook.EIP_MADDRESSBOOK_COMPANY_PROPERTY
    // + "."
    // + EipMAddressbookCompany.COMPANY_NAME_KANA_PROPERTY,
    // "%" + word + "%");
    // Expression exp23 =
    // ExpressionFactory.likeExp(
    // EipMAddressbook.EIP_MADDRESSBOOK_COMPANY_PROPERTY
    // + "."
    // + EipMAddressbookCompany.TELEPHONE_PROPERTY,
    // "%" + word + "%");
    Expression exp21 =
      ExpressionFactory.likeExp(
        EipMAddressbook.EIP_TADDRESSBOOK_GROUP_MAP_PROPERTY
          + "."
          + EipTAddressbookGroupMap.EIP_TADDRESS_GROUP_PROPERTY
          + "."
          + EipMAddressGroup.GROUP_NAME_PROPERTY,
        "%" + word + "%");
    // change end

    Expression exp31 =
      ExpressionFactory.likeExp(EipMAddressbook.FIRST_NAME_PROPERTY, "%"
        + transWord
        + "%");
    Expression exp32 =
      ExpressionFactory.likeExp(EipMAddressbook.LAST_NAME_PROPERTY, "%"
        + transWord
        + "%");
    Expression exp33 =
      ExpressionFactory.likeExp(EipMAddressbook.FIRST_NAME_KANA_PROPERTY, "%"
        + transWord
        + "%");
    Expression exp34 =
      ExpressionFactory.likeExp(EipMAddressbook.LAST_NAME_KANA_PROPERTY, "%"
        + transWord
        + "%");

    // change start
    // Expression exp35 =
    // ExpressionFactory.likeExp(
    // EipMAddressbook.EIP_MADDRESSBOOK_COMPANY_PROPERTY
    // + "."
    // + EipMAddressbookCompany.COMPANY_NAME_PROPERTY,
    // "%" + transWord + "%");
    // Expression exp36 =
    // ExpressionFactory.likeExp(
    // EipMAddressbook.EIP_MADDRESSBOOK_COMPANY_PROPERTY
    // + "."
    // + EipMAddressbookCompany.COMPANY_NAME_KANA_PROPERTY,
    // "%" + transWord + "%");
    Expression exp35 =
      ExpressionFactory.likeExp(
        EipMAddressbook.EIP_TADDRESSBOOK_GROUP_MAP_PROPERTY
          + "."
          + EipTAddressbookGroupMap.EIP_TADDRESS_GROUP_PROPERTY
          + "."
          + EipMAddressGroup.GROUP_NAME_PROPERTY,
        "%" + transWord + "%");
    // change end

    if (word != null && !"".equals(word)) {
      query.andQualifier(exp11.orExp(exp12).orExp(exp13).orExp(exp14).orExp(
        exp15).orExp(exp16).orExp(exp17)
      // add start
        .orExp(exp18)
        // add end
        .orExp(exp21)
        // del start
        // .orExp(exp22)
        // .orExp(exp23)
        // del end
        .orExp(exp31)
        .orExp(exp32)
        .orExp(exp33)
        .orExp(exp34)
        .orExp(exp35)
      // del start
        // .orExp(exp36)
        // del end
        );
    }

    return query;
  }

  /**
   * アドレス帳社外グループ選択プルダウン用データ取得
   * 
   * @param rundata
   *            JetSpeedランデータ
   * @param context
   *            JetSpeedコンテキスト
   */
  @Override
  public void loadGroups(RunData rundata, Context context) {
    groupList = new ArrayList<AddressBookGroupResultData>();
    try {
      // 自分がオーナのグループ指定
      SelectQuery<EipMAddressGroup> query =
        Database.query(EipMAddressGroup.class);
      Expression exp =
        ExpressionFactory.matchExp(EipMAddressGroup.OWNER_ID_PROPERTY, Integer
          .valueOf(ALEipUtils.getUserId(rundata)));
      query.setQualifier(exp);

      List<EipMAddressGroup> aList = query.fetchList();
      int size = aList.size();
      for (int i = 0; i < size; i++) {
        EipMAddressGroup record = aList.get(i);
        AddressBookGroupResultData rd = new AddressBookGroupResultData();
        rd.initField();
        rd.setGroupId(record.getGroupId().longValue());
        rd.setGroupName(record.getGroupName());
        groupList.add(rd);
      }
    } catch (Exception ex) {
      // change start
      // logger.error("Exception", ex);
      String msg =
        "会社グループプルダウン用のデータ取得に失敗しました。["
          + ALEipUtils.getUserLoginName(loginuserid)
          + "]";
      logger.error(msg, ex);
      // change end
    }
  }

  /**
   * グループリストを取得します。
   * 
   * @return グループリスト
   */
  @Override
  public List<AddressBookGroupResultData> getGroupList() {
    return groupList;
  }

  /**
   * マイグループリストを取得します。
   * 
   * @return マイグループリスト
   */
  @Override
  public List<ALEipGroup> getMyGroupList() {
    return myGroupList;
  }

  /**
   * アクセス権限チェック用メソッド。 アクセス権限の機能名を返します。
   * 
   * @return アクセス権限の機能名
   */
  @Override
  public String getAclPortletFeature() {
    return ALAccessControlConstants.POERTLET_FEATURE_ADDRESSBOOK_ADDRESS_OUTSIDE;
  }

  /**
   * 表示用テンプレートファイル名取得
   * 
   * @return 表示用テンプレートファイル名
   */
  @Override
  public String getTemplateFilePath() {
    return "portlets/html/ja/ajax-addressbook-list.vm";
  }

  /**
   * ソート用の <code>SelectQuery</code> を構築します。
   * 
   * @param query
   *            SQLオブジェクト
   * @param rundata
   *            JetSpeedランデータ
   * @param context
   *            JetSpeedコンテキスト
   * @return ソート用の構築済みSQLオブジェクト
   */
  @Override
  protected SelectQuery<EipMAddressbook> buildSelectQueryForListViewSort(
      SelectQuery<EipMAddressbook> query, RunData rundata, Context context) {
    String sort = ALEipUtils.getTemp(rundata, context, LIST_SORT_STR);
    String sort_type = ALEipUtils.getTemp(rundata, context, LIST_SORT_TYPE_STR);
    String crt_key = null;

    Attributes map = getColumnMap();
    if (sort == null) {
      return query;
    }
    crt_key = map.getValue(sort);
    if (crt_key == null) {
      return query;
    }

    if ("name_kana".equals(sort)) {
      if (sort_type != null
        && ALEipConstants.LIST_SORT_TYPE_DESC.equals(sort_type)) {
        query.orderDesending(crt_key);
        // add start
        query.orderDesending(EipMAddressbook.UPDATE_DATE_PROPERTY);
        // add end
      } else {
        query.orderAscending(crt_key);
        // add start
        query.orderAscending(EipMAddressbook.UPDATE_DATE_PROPERTY);
        // add end
        sort_type = ALEipConstants.LIST_SORT_TYPE_ASC;
      }
    } else if ("company_name".equals(sort)) {

      String crt_sub_key = map.getValue("name_kana");

      // add start
      // String first_name_key = map.getValue("first_name_kana");
      // add end

      if (sort_type != null
        && ALEipConstants.LIST_SORT_TYPE_DESC.equals(sort_type)) {
        query.orderDesending(crt_key);
        query.orderDesending(crt_sub_key);
        // add start
        // query.orderDesending(first_name_key);
        // add end
        // add start
        query.orderDesending(EipMAddressbook.UPDATE_DATE_PROPERTY);
        // add end
      } else {
        query.orderAscending(crt_key);
        query.orderAscending(crt_sub_key);
        // add start
        // query.orderAscending(first_name_key);
        // add end
        // add start
        query.orderAscending(EipMAddressbook.UPDATE_DATE_PROPERTY);
        // add end
        sort_type = ALEipConstants.LIST_SORT_TYPE_ASC;
      }
    }

    current_sort = sort;
    current_sort_type = sort_type;
    return query;
  }
}
