/*
 * 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.addressbookuser.util;

import java.util.ArrayList;
import java.util.List;

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 com.aimluck.eip.addressbookuser.beans.AddressBookUserEmailLiteBean;
import com.aimluck.eip.addressbookuser.beans.AddressBookUserGroupLiteBean;
import com.aimluck.eip.addressbookuser.beans.AddressBookUserLiteBean;
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.orm.Database;
import com.aimluck.eip.orm.query.SelectQuery;
import com.aimluck.eip.util.ALEipUtils;

/**
 * ユーティリティクラスです。 <br />
 * 
 */
public class AddressBookUserUtils {

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

  // add by motegi start
  public static final String EMPTY_COMPANY_NAME = "未所属";

  /**
   * 
   * @param rundata
   * @return
   */
  public static List<AddressBookUserLiteBean> getAddressBookUserLiteBeansFromGroup(
      String groupid, int loginuserid) {
    List<AddressBookUserLiteBean> list =
      new ArrayList<AddressBookUserLiteBean>();

    try {
      SelectQuery<EipMAddressbook> query =
        getSelectQueryForAddressBook(groupid, loginuserid);

      List<EipMAddressbook> addressbook_list = query.fetchList();

      for (EipMAddressbook record : addressbook_list) {
        AddressBookUserLiteBean address = new AddressBookUserLiteBean();
        address.initField();
        address.setAddressId(record.getAddressId());
        address.setFullName(record.getLastName(), record.getFirstName());
        list.add(address);
      }
    } catch (Exception e) {
      logger.error("[AddressBookUserUtils]", e);
    }

    return list;
  }

  /**
   * 
   * @param rundata
   * @return
   */
  public static List<AddressBookUserGroupLiteBean> getAddressBookUserGroupLiteBeans(
      RunData rundata) {
    List<AddressBookUserGroupLiteBean> list =
      new ArrayList<AddressBookUserGroupLiteBean>();

    try {
      // 自分がオーナのグループを取得
      SelectQuery<EipMAddressGroup> query =
        Database.query(EipMAddressGroup.class);

      Expression exp =
        ExpressionFactory.matchExp(EipMAddressGroup.OWNER_ID_PROPERTY, Integer
          .valueOf(ALEipUtils.getUserId(rundata)));
      query.setQualifier(exp).orderAscending(
        EipMAddressGroup.GROUP_NAME_PROPERTY);

      List<EipMAddressGroup> addressgroup_list = query.fetchList();
      for (EipMAddressGroup record : addressgroup_list) {
        AddressBookUserGroupLiteBean bean = new AddressBookUserGroupLiteBean();
        bean.initField();
        bean.setGroupId(record.getGroupId());
        bean.setName(record.getGroupName());
        list.add(bean);
      }
    } catch (Exception e) {
      logger.error("[AddressBookUserUtils]", e);
    }
    return list;
  }

  /**
   * 所属グループよりWebメール用個人アドレス(社外グループ)一覧取得
   * 
   * @param rundata
   *          実行データ
   * @param loginuserid
   *          ログインユーザーID
   * @return Webメール用個人アドレス一覧
   */
  public static List<AddressBookUserEmailLiteBean> getAddressBookUserEmailLiteBeansFromGroup(
      String groupid, int loginuserid) {
    List<AddressBookUserEmailLiteBean> list =
      new ArrayList<AddressBookUserEmailLiteBean>();

    try {
      SelectQuery<EipMAddressbook> query =
        getSelectQueryForAddressBook(groupid, loginuserid);

      List<EipMAddressbook> addressbook_list = query.fetchList();

      for (EipMAddressbook record : addressbook_list) {
        AddressBookUserEmailLiteBean bean = new AddressBookUserEmailLiteBean();
        bean.initField();
        bean.setAddressId(record.getAddressId());
        bean.setFullName(record.getLastName(), record.getFirstName());
        bean.setEmail(record.getEmail());
        list.add(bean);
      }
    } catch (Exception e) {
      logger.error("[AddressBookUserUtils]", e);
    }

    return list;
  }

  /**
   * アドレス帳検索クエリー取得
   * 
   * @param groupid
   *          所属グループID
   * @param loginuserid
   *          ログインユーザーID
   * @return アドレス帳検索クエリー
   */
  private static SelectQuery<EipMAddressbook> getSelectQueryForAddressBook(
      String groupid, int loginuserid) {
    SelectQuery<EipMAddressbook> query = Database.query(EipMAddressbook.class);

    Expression exp21 =
      ExpressionFactory.matchExp(EipMAddressbook.PUBLIC_FLAG_PROPERTY, "T");
    Expression exp22 =
      ExpressionFactory
        .matchExp(EipMAddressbook.OWNER_ID_PROPERTY, loginuserid);
    Expression exp23 =
      ExpressionFactory.matchExp(EipMAddressbook.PUBLIC_FLAG_PROPERTY, "F");
    query.setQualifier(exp21.orExp(exp22.andExp(exp23)));

    if (groupid != null && !"".equals(groupid) && !"all".equals(groupid)) {
      Expression exp31 =
        ExpressionFactory.matchDbExp(
          EipMAddressbook.EIP_TADDRESSBOOK_GROUP_MAP_PROPERTY
            + "."
            + EipTAddressbookGroupMap.EIP_TADDRESS_GROUP_PROPERTY
            + "."
            + EipMAddressGroup.GROUP_ID_PK_COLUMN,
          groupid);
      query.andQualifier(exp31);
    }
    // add start
    // 運用課題No.60
    query.orderAscending(EipMAddressbook.LAST_NAME_KANA_PROPERTY);
    // add end

    return query;
  }

  // add by motegi start
  /**
   * アドレス帳社外グループ追加（編集）画面の個人アドレスリスト用
   * 
   * @param rundata
   * @return
   * @throws Exception
   */
  public static List<AddressBookUserLiteBean> getAddressBookUserLiteBeansWithoutGroup(
      int loginuserid) throws Exception {
    List<AddressBookUserLiteBean> list =
      new ArrayList<AddressBookUserLiteBean>();

    try {

      EipMAddressGroup defaultGroup =
        AddressBookUserUtils.getDefaultEipMAddressGroup();

      int defaultGroupId = defaultGroup.getGroupId();

      SelectQuery<EipMAddressbook> query =
        Database.query(EipMAddressbook.class);

      Expression exp1 =
        ExpressionFactory.matchDbExp(
          EipMAddressbook.EIP_TADDRESSBOOK_GROUP_MAP_PROPERTY
            + "."
            + EipTAddressbookGroupMap.EIP_TADDRESS_GROUP_PROPERTY
            + "."
            + EipMAddressGroup.GROUP_ID_PK_COLUMN,
          defaultGroupId);

      query.setQualifier(exp1);

      Expression exp2 =
        ExpressionFactory.matchExp(
          EipMAddressbook.OWNER_ID_PROPERTY,
          loginuserid);

      query.andQualifier(exp2);
      query.orderAscending(EipMAddressbook.LAST_NAME_KANA_PROPERTY);

      List<EipMAddressbook> addressbook_list = query.fetchList();
      if (addressbook_list != null && addressbook_list.size() > 0) {
        for (EipMAddressbook record : addressbook_list) {
          AddressBookUserLiteBean address = new AddressBookUserLiteBean();
          address.initField();
          address.setAddressId(record.getAddressId());
          address.setFullName(record.getLastName(), record.getFirstName());
          list.add(address);
        }
      }
    } catch (Exception e) {
      throw e;
    }

    return list;
  }

  /**
   * 指定ユーザーが登録したアドレス帳社外グループリストを取得する。 先頭に”未所属”を追加する。
   * 
   * @param loginuserid
   * @return
   * @throws Exception
   */
  public static List<AddressBookUserGroupLiteBean> getEipMAddressGroup(
      int loginuserid) throws Exception {

    List<AddressBookUserGroupLiteBean> groupList =
      new ArrayList<AddressBookUserGroupLiteBean>();

    SelectQuery<EipMAddressGroup> query =
      Database.query(EipMAddressGroup.class);
    Expression exp =
      ExpressionFactory.matchExp(
        EipMAddressGroup.OWNER_ID_PROPERTY,
        loginuserid);
    query.setQualifier(exp);
    query.orderAscending(EipMAddressGroup.GROUP_NAME_PROPERTY);

    List<EipMAddressGroup> aList = query.fetchList();

    int size = aList.size();
    for (int i = 0; i < size; i++) {
      EipMAddressGroup record = aList.get(i);
      AddressBookUserGroupLiteBean rd = new AddressBookUserGroupLiteBean();
      rd.initField();
      rd.setGroupId(record.getGroupId().intValue());
      rd.setName(record.getGroupName());
      groupList.add(rd);
    }

    // add by motegi start
    // "未所属"を先頭に追加
    EipMAddressGroup defaultGroup =
      AddressBookUserUtils.getDefaultEipMAddressGroup();
    AddressBookUserGroupLiteBean r = new AddressBookUserGroupLiteBean();
    r.initField();
    r.setGroupId(defaultGroup.getGroupId().intValue());
    r.setName(EMPTY_COMPANY_NAME);
    groupList.add(0, r);
    // add end

    return groupList;
  }

  /**
   * 未分類の会社情報を取得する。
   * 
   * @param rundata
   * @param context
   * @return
   * @throws Exception
   */
  public static EipMAddressGroup getDefaultEipMAddressGroup() throws Exception {

    final int AIPO_SYSTEM_USER_ID = 1;
    try {
      SelectQuery<EipMAddressGroup> query =
        Database.query(EipMAddressGroup.class);
      Expression exp1 =
        ExpressionFactory.matchExp(
          EipMAddressGroup.OWNER_ID_PROPERTY,
          AIPO_SYSTEM_USER_ID);
      query.setQualifier(exp1);

      List<EipMAddressGroup> groups = query.fetchList();
      if (groups == null || groups.size() == 0) {
        // 指定したカテゴリIDのレコードが見つからない場合
        logger.debug("[AddressBook] Not found Group ID...");
        throw new Exception();
      }
      return groups.get(0);
    } catch (Exception ex) {
      logger.error("「未所属」社外グループの取得に失敗しました。" + ex);
      throw ex;
    }
  }
}
