/*
 * 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 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 General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 */
package com.aimluck.eip.account;

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

import org.apache.cayenne.access.DataContext;
import org.apache.cayenne.access.Transaction;
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.eip.cayenne.om.account.AvzMGroupsend;
import com.aimluck.eip.cayenne.om.account.AvzMGroupsendPosition;
import com.aimluck.eip.cayenne.om.account.AvzMUserGroupsend;
import com.aimluck.eip.common.ALAbstractCheckList;
import com.aimluck.eip.common.ALEipManager;
import com.aimluck.eip.orm.Database;
import com.aimluck.eip.orm.query.ResultList;
import com.aimluck.eip.orm.query.SelectQuery;

/**
 * グループ送信情報の複数削除を行うためのクラスです。 <BR>
 * 
 */
public class AccountGroupSendMultiDelete extends ALAbstractCheckList {

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

  /**
   * 一括削除処理
   * 
   * @param action
   *            アクションクラス
   * @param rundata
   *            JetSpeedランデータ
   * @param context
   *            JetSpeedコンテキスト
   * @param values
   *            グループ送信IDリスト
   * @param msgList
   *            エラーメッセージリスト
   * @return 処理結果(正常：true、異常:false)
   * @see com.aimluck.eip.common.ALAbstractCheckList#action(org.apache.turbine.util.RunData,
   *      org.apache.velocity.context.Context, java.util.ArrayList,
   *      java.util.ArrayList)
   */
  @Override
  protected boolean action(RunData rundata, Context context,
      List<String> values, List<String> msgList) {

    // 標準のトランザクション（オートコミット）
    Transaction baseTx = Transaction.getThreadTransaction();

    DataContext dataContext = DataContext.getThreadDataContext();

    // 自己管理トランザクション
    Transaction tx =
      Transaction.internalTransaction(DataContext
        .getThreadDataContext()
        .getParentDataDomain()
        .getTransactionDelegate());

    // 標準のトランザクションを自己管理トランザクションに置き換えます。
    Transaction.bindThreadTransaction(tx);

    try {
      // トランザクション開始
      tx.begin();

      List<Integer> ids = new ArrayList<Integer>();
      int size = values.size();
      for (int i = 0; i < size; i++) {
        ids.add(Integer.valueOf(values.get(i)));
      }

      SelectQuery<AvzMGroupsend> query = Database.query(AvzMGroupsend.class);
      Expression exp1 =
        ExpressionFactory.inDbExp(AvzMGroupsend.GROUPSEND_ID_PK_COLUMN, ids);
      query.setQualifier(exp1);

      ResultList<AvzMGroupsend> entities = query.getResultList();
      if (entities == null || entities.size() == 0) {
        return false;
      }
      for (AvzMGroupsend entity : entities) {
        SelectQuery<AvzMUserGroupsend> queryAvzMUserGroupsend =
          Database.query(AvzMUserGroupsend.class);
        Expression exp =
          ExpressionFactory.matchExp(
            AvzMUserGroupsend.GROUPSEND_ID_PROPERTY,
            entity.getGroupsendId());
        queryAvzMUserGroupsend.setQualifier(exp);
        ResultList<AvzMUserGroupsend> list =
          queryAvzMUserGroupsend.getResultList();
        if (list != null && list.size() != 0) {
          Database.deleteAll(list);
        }
        Database.delete(entity.getAvzMGroupsendPositionArray());
        Database.delete(entity);
        dataContext.commitChanges();
      }

      // 他のグループ送信の順番を変更する．
      SelectQuery<AvzMGroupsendPosition> p_query =
        Database.query(AvzMGroupsendPosition.class);
      p_query.orderAscending(AvzMGroupsendPosition.POSITION_PROPERTY);
      List<AvzMGroupsendPosition> entityPositions = p_query.fetchList();

      if (entityPositions != null && entityPositions.size() > 0) {

        int PositionSize = entityPositions.size();
        for (int i = 0; i < PositionSize; i++) {
          AvzMGroupsendPosition entityPosition = entityPositions.get(i);
          entityPosition.setPosition(Integer.valueOf(i + 1));
          dataContext.commitChanges();
        }
      }

      Database.commit();

      ALEipManager.getInstance().reloadGroupSend();

    } catch (Exception ex) {
      Database.rollback();
      String msg = "グループ送信情報の一括削除に失敗しました。";
      logger.error(msg, ex);
      msgList.add(msg);
      return false;
    } finally {
      // 自己管理トランザクションを標準のトランザクションに戻します。
      Transaction.bindThreadTransaction(baseTx);
    }
    return true;
  }
}
