/*
 * 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 org.apache.cayenne.exp.Expression;
import org.apache.cayenne.exp.ExpressionFactory;
import org.apache.jetspeed.om.security.Group;
import org.apache.jetspeed.om.security.JetspeedUser;
import org.apache.jetspeed.om.security.Role;
import org.apache.jetspeed.services.JetspeedSecurity;
import org.apache.jetspeed.services.PsmlManager;
import org.apache.jetspeed.services.security.GroupException;
import org.apache.jetspeed.services.security.JetspeedSecurityException;

import com.aimluck.eip.cayenne.om.security.TurbineGroup;
import com.aimluck.eip.cayenne.om.security.TurbineRole;
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.services.security.ALGroupManagement;

/**
 * グループを管理するクラスALGroupManagementのコピークラスです。<br>
 * unjoinGroup、joinGroupを変更しています。
 */
public class ALBatchGroupUtils {

  protected static String defaultRole = "user";

  private final static boolean cascadeDelete = true;

  /**
   * @see {@link ALGroupManagement#unjoinGroup(String, String)}
   */
  public static void unjoinGroup(String username, String groupname)
      throws JetspeedSecurityException {
    unjoinGroup(username, groupname, defaultRole);
  }

  /**
   * コミット、ロールバックをコメントアウトしました。<br>
   * 
   * @see {@link ALGroupManagement#unjoinGroup(String, String, String)}
   */
  public static void unjoinGroup(String username, String groupname,
      String rolename) throws JetspeedSecurityException {
    try {
      JetspeedUser user = JetspeedSecurity.getUser(username);
      Group group = JetspeedSecurity.getGroup(groupname);
      Role role = JetspeedSecurity.getRole(rolename);

      Expression exp1 =
        ExpressionFactory.matchDbExp(TurbineUser.USER_ID_PK_COLUMN, Integer
          .valueOf(user.getUserId()));
      Expression exp2 =
        ExpressionFactory.matchDbExp(TurbineGroup.GROUP_ID_PK_COLUMN, Integer
          .valueOf(group.getId()));
      Expression exp3 =
        ExpressionFactory.matchDbExp(TurbineRole.ROLE_ID_PK_COLUMN, Integer
          .valueOf(role.getId()));
      SelectQuery<TurbineUserGroupRole> query =
        Database.query(TurbineUserGroupRole.class);
      query.setQualifier(exp1);
      query.andQualifier(exp2);
      query.andQualifier(exp3);

      query.deleteAll();

      // Database.commit();

    } catch (Exception e) {
      throw new GroupException("Unjoin group '"
        + groupname
        + "' to user '"
        + username
        + "' failed: ", e);
    }
  }

  /**
   * @see {@link ALGroupManagement#joinGroup(String, String)}
   */
  public static void joinGroup(String username, String groupname)
      throws JetspeedSecurityException {
    joinGroup(username, groupname, defaultRole);
  }

  /**
   * コミット、ロールバックをコメントアウトしました。<br>
   * 
   * @see {@link ALGroupManagement#joinGroup(String, String, String)}
   */
  public static void joinGroup(String username, String groupname,
      String rolename) throws JetspeedSecurityException {
    try {
      JetspeedUser user = JetspeedSecurity.getUser(username);
      Group group = JetspeedSecurity.getGroup(groupname);
      Role role = JetspeedSecurity.getRole(rolename);

      // 新規オブジェクトモデル
      TurbineUserGroupRole user_group_role =
        Database.create(TurbineUserGroupRole.class);
      TurbineUser tuser =
        Database.get(TurbineUser.class, Integer.valueOf(user.getUserId()));

      user_group_role.setTurbineUser(tuser);
      user_group_role.setTurbineGroup((TurbineGroup) group);
      user_group_role.setTurbineRole((TurbineRole) role);
      // Database.commit();

    } catch (Exception e) {
      // Database.rollback();
      throw new GroupException("Join group '"
        + groupname
        + "' to user '"
        + username
        + "' failed: ", e);
    }
  }

  /**
   * コミット、ロールバックをコメントアウトしました。<br>
   * 
   * @see {@link ALGroupManagement#removeGroup(String)}
   */
  public static void removeGroup(String groupname)
      throws JetspeedSecurityException {
    try {
      Group group = JetspeedSecurity.getGroup(groupname);

      if (cascadeDelete) {
        Expression exp =
          ExpressionFactory.matchDbExp(TurbineGroup.GROUP_ID_PK_COLUMN, Integer
            .valueOf(group.getId()));
        SelectQuery<TurbineUserGroupRole> query =
          Database.query(TurbineUserGroupRole.class, exp);

        query.deleteAll();

      }
      Database.delete((TurbineGroup) group);

      PsmlManager.removeGroupDocuments(group);

      // Database.commit();
    } catch (Exception e) {
      // Database.rollback();
      throw new GroupException("Failed to remove group '" + groupname + "'", e);
    } finally {

    }

  }

}
