/*
 * Aipo is a groupware program developed by Aimluck,Inc.
 * http://aipostyle.com/
 * 
 * Copyright(C) 2009 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.circulation;

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

import org.apache.cayenne.access.DataContext;
import org.apache.cayenne.exp.Expression;
import org.apache.cayenne.exp.ExpressionFactory;
import org.apache.cayenne.query.SelectQuery;
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.portlet.AvzTCirculationCategory;
import com.aimluck.eip.cayenne.om.portlet.AvzTCirculationRequest;
import com.aimluck.eip.cayenne.om.portlet.auto._AvzTCirculationCategory;
import com.aimluck.eip.cayenne.om.portlet.auto._AvzTCirculationRequest;
import com.aimluck.eip.circulation.util.CirculationUtils;
import com.aimluck.eip.common.ALAbstractCheckList;
import com.aimluck.eip.orm.DatabaseOrmService;

/**
 * 回覧板カテゴリの複数削除を行うためのクラスです。 <BR>
 * 
 */
public class CirculationCategoryMultiDelete extends ALAbstractCheckList {

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

  /**
   * 
   * @param rundata
   * @param context
   * @param values
   * @param msgList
   * @return
   * @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) {

    DataContext dataContext = DatabaseOrmService.getInstance().getDataContext();

    try {

      List<Integer> intValues = new ArrayList<Integer>();
      int valuesize = values.size();
      for (int i = 0; i < valuesize; i++) {
        String value = values.get(i);
        if (!"1".equals(value)) {
          intValues.add(Integer.valueOf(value));
        }
      }

      SelectQuery query = new SelectQuery(AvzTCirculationCategory.class);
      Expression exp1 =
        ExpressionFactory.inDbExp(
          _AvzTCirculationCategory.CATEGORY_ID_PK_COLUMN,
          intValues);
      query.setQualifier(exp1);
      List categorylist = dataContext.performQuery(query);
      if (categorylist == null || categorylist.size() == 0) {
        return false;
      }

      // カテゴリを削除
      dataContext.deleteObjects(categorylist);

      // これらカテゴリに含まれる依頼をカテゴリ「未分類」に移す。
      List<Integer> categoryIds = new ArrayList<Integer>();
      AvzTCirculationCategory category = null;
      int catesize = categorylist.size();
      for (int i = 0; i < catesize; i++) {
        category = (AvzTCirculationCategory) categorylist.get(i);
        categoryIds.add(category.getCategoryId());
      }

      SelectQuery reqquery = new SelectQuery(AvzTCirculationRequest.class);
      Expression reqexp1 =
        ExpressionFactory.inDbExp(
          _AvzTCirculationRequest.TO_AVZ_TCIRCULATION_CATEGORY_PROPERTY
            + "."
            + _AvzTCirculationCategory.CATEGORY_ID_PK_COLUMN,
          categoryIds);
      reqquery.setQualifier(reqexp1);
      List requests = dataContext.performQuery(reqquery);
      if (requests != null && requests.size() > 0) {
        AvzTCirculationRequest request = null;
        AvzTCirculationCategory defaultCategory =
          CirculationUtils.getAvzTCirculationCategory(dataContext, Long
            .valueOf(1));
        int size = requests.size();
        for (int i = 0; i < size; i++) {
          request = (AvzTCirculationRequest) requests.get(i);
          request.setToAvzTCirculationCategory(defaultCategory);

          // 回覧板カテゴリを削除
          dataContext.deleteObject(category);
        }
      }

      dataContext.commitChanges();

      CirculationUtils.clearFilter(rundata, context);

    } catch (Exception ex) {
      logger.error("Exception", ex);
      dataContext.rollbackChanges();
      return false;
    }
    return true;
  }

}
