/*
 * 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 aipo.batch.utils;

import java.util.Date;
import java.util.List;

import org.apache.cayenne.exp.Expression;
import org.apache.cayenne.exp.ExpressionFactory;
import org.apache.jetspeed.om.security.JetspeedUser;
import org.apache.jetspeed.om.security.UserNamePrincipal;
import org.apache.jetspeed.services.JetspeedSecurity;
import org.apache.jetspeed.services.PsmlManager;

import com.aimluck.eip.account.util.AccountUtils;
import com.aimluck.eip.cayenne.om.account.AvzMUserGroupsend;
import com.aimluck.eip.cayenne.om.account.AvzMUserRole;
import com.aimluck.eip.cayenne.om.account.EipMUserPosition;
import com.aimluck.eip.cayenne.om.portlet.AvzTScheduleAcl;
import com.aimluck.eip.cayenne.om.portlet.EipMAddressGroup;
import com.aimluck.eip.cayenne.om.portlet.EipMAddressbook;
import com.aimluck.eip.cayenne.om.portlet.EipMMailAccount;
import com.aimluck.eip.cayenne.om.portlet.EipTBlog;
import com.aimluck.eip.cayenne.om.portlet.EipTBlogFootmarkMap;
import com.aimluck.eip.cayenne.om.portlet.EipTTodo;
import com.aimluck.eip.cayenne.om.portlet.EipTTodoCategory;
import com.aimluck.eip.cayenne.om.security.TurbineUser;
import com.aimluck.eip.cayenne.om.security.TurbineUserGroupRole;
import com.aimluck.eip.orm.Database;
import com.aimluck.eip.orm.query.SelectQuery;
import com.aimluck.eip.util.ALEipUtils;

/**
 * ユーザーアカウントのユーティリティクラスAccountUtilsのコピークラスです。<br>
 * deleteUserを変更しています。<br>
 * deleteUserのコミット、ロールバック処理をコメントアウト<br>
 */
public class ALBatchAccountUtils {

  /**
   * 指定ユーザーの削除を行なう(AccountUtils.deleteUserのコピー) <br>
   * パラメータmsgListを削除<br>
   * deleteAccountのmsgListをnullに<br>
   * コミット、ロールバック処理をコメントアウト<br>
   * ダミーユーザーIDに更新する処理を修正<br>
   * 
   * @param user
   *          削除対象ユーザー
   * @return 処理結果（正常:true、異常:false）
   * @throws Exception
   * @see {@link AccountUtils#deleteUser(TurbineUser, List)}
   */
  public static boolean deleteUser(TurbineUser user) throws Exception {

    user.setPositionId(Integer.valueOf(0));
    user.setDisabled("T");

    String userId = user.getUserId().toString();

    // 対象ユーザのユーザーグループロールをすべて削除する
    SelectQuery<TurbineUserGroupRole> query2 =
      Database.query(TurbineUserGroupRole.class);
    Expression exp2 =
      ExpressionFactory.matchExp(
        TurbineUserGroupRole.TURBINE_USER_PROPERTY,
        userId);
    query2.setQualifier(exp2);
    List<TurbineUserGroupRole> list4 = query2.fetchList();

    TurbineUserGroupRole ugr = null;
    for (int i = 0; i < list4.size(); i++) {
      ugr = list4.get(i);
      Database.delete(ugr);
    }

    // add by motegi start
    // スケジュール制御
    String deleteAvzTScheduleAcl =
      "DELETE FROM avz_t_schedule_acl WHERE USER_ID = #bind($userId 'INTEGER')";
    Database.sql(AvzTScheduleAcl.class, deleteAvzTScheduleAcl).param(
      "userId",
      userId).execute();

    // ユーザーグループ送信削除
    String deleteAvzMUserGroupsend =
      "DELETE FROM avz_m_user_groupsend WHERE USER_ID = #bind($userId 'INTEGER')";
    Database.sql(AvzMUserGroupsend.class, deleteAvzMUserGroupsend).param(
      "userId",
      userId).execute();

    // ユーザー役割削除
    String deleteAvzMUserRole =
      "DELETE FROM avz_m_user_role WHERE USER_ID = #bind($userId 'INTEGER')";
    Database
      .sql(AvzMUserRole.class, deleteAvzMUserRole)
      .param("userId", userId)
      .execute();

    // メールアカウント削除
    List<EipMMailAccount> accountList =
      AccountUtils.getEipMMailAccounts(Integer.parseInt(userId));
    if (accountList != null && accountList.size() > 0) {
      for (EipMMailAccount obj : accountList) {
        // AccountUtils.deleteAccount(obj.getAccountId(), msgList);
        AccountUtils.deleteAccount(obj.getAccountId(), null);
      }
    }

    // 個人アドレス帳削除
    List<EipMAddressbook> addressList =
      AccountUtils.getEipMAddressbooks(Integer.parseInt(userId));
    if (addressList != null && addressList.size() > 0) {
      for (EipMAddressbook obj : addressList) {
        String deleteEipMAddressGroup =
          "DELETE FROM eip_t_addressbook_group_map WHERE ADDRESS_ID = #bind($addressId 'INTEGER')";
        Database.sql(EipMAddressGroup.class, deleteEipMAddressGroup).param(
          "addressId",
          obj.getAddressId()).execute();
      }
    }

    String deleteEipMAddressGroup =
      "DELETE FROM eip_m_address_group WHERE OWNER_ID = #bind($userId 'INTEGER')";
    Database.sql(EipMAddressGroup.class, deleteEipMAddressGroup).param(
      "userId",
      userId).execute();

    String deleteEipMAddressbook =
      "DELETE FROM eip_m_addressbook WHERE OWNER_ID = #bind($userId 'INTEGER')";
    Database.sql(EipMAddressbook.class, deleteEipMAddressbook).param(
      "userId",
      userId).execute();

    // ユーザー表示順位削除
    String deleteEipMUserPosition =
      "DELETE FROM eip_m_user_position WHERE USER_ID = #bind($userId 'INTEGER')";
    Database.sql(EipMUserPosition.class, deleteEipMUserPosition).param(
      "userId",
      userId).execute();
    // add end

    // ToDoを削除する
    String sql4 =
      "DELETE FROM eip_t_todo WHERE USER_ID = #bind($userId 'INTEGER')";
    Database.sql(EipTTodo.class, sql4).param("userId", userId).execute();

    String sql5 =
      "DELETE FROM eip_t_todo_category WHERE USER_ID = #bind($userId 'INTEGER')";
    Database
      .sql(EipTTodoCategory.class, sql5)
      .param("userId", userId)
      .execute();

    // ブログを削除する
    String sql6 =
      "DELETE FROM eip_t_blog WHERE OWNER_ID = #bind($userId 'INTEGER')";
    Database.sql(EipTBlog.class, sql6).param("userId", userId).execute();

    // ブログの足跡を削除する
    String sql7 =
      "DELETE FROM eip_t_blog_footmark_map WHERE USER_ID = #bind($userId 'INTEGER')";
    Database
      .sql(EipTBlogFootmarkMap.class, sql7)
      .param("userId", userId)
      .execute();

    // ワークフロー自動承認
    AccountUtils.acceptWorkflow(Integer.parseInt(userId));

    // ソーシャルアプリ関連データ削除
    ALBatchDefaultSocialApplicationHanlderUtils.deleteUserData(user
      .getLoginName());

    // PSMLを削除
    JetspeedUser juser =
      JetspeedSecurity.getUser(new UserNamePrincipal(user.getLoginName()));
    PsmlManager.removeUserDocuments(juser);

    // ユーザー名の先頭に"dummy_userid_"を追加

    // すでにダミー文字列が付いている場合は追加しない。
    // modify start
    // String dummy_user_name = ALEipUtils.dummy_user_head + userId + "_" +
    // user.getLoginName();
    // user.setLoginName(dummy_user_name);
    // user.setModified(new Date());
    if (!user.getLoginName().startsWith(ALEipUtils.dummy_user_head)) {
      String dummy_user_name =
        ALEipUtils.dummy_user_head + userId + "_" + user.getLoginName();
      user.setLoginName(dummy_user_name);
      user.setModified(new Date());
    }
    // modify end
    return true;

  }

}
