/*
 * 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.jetspeed.om.profile.BaseProfile;
import org.apache.jetspeed.om.security.JetspeedUser;
import org.apache.jetspeed.services.JetspeedSecurity;
import org.apache.jetspeed.services.Profiler;
import org.apache.jetspeed.services.logging.JetspeedLogFactoryService;
import org.apache.jetspeed.services.logging.JetspeedLogger;
import org.apache.jetspeed.services.security.JetspeedSecurityException;
import org.apache.jetspeed.services.security.UserException;

import com.aimluck.eip.orm.Database;
import com.aimluck.eip.services.security.ALUserManagement;

/**
 * ユーザーを管理するクラスALUserManagementのコピークラスです。<br>
 * addDefaultPSML、grantRolesを変更しています。<br>
 */
public class ALBatchUserUtils {

  private static final JetspeedLogger logger =
    JetspeedLogFactoryService.getLogger(ALBatchUserUtils.class.getName());

  private final static String[] DEFAULT_CONFIG_NEWUSER_ROLES = { "user" };

  private final static String[] DEFAULT_CONFIG_NEW_ADMINUSER_ROLES =
    { "user", "admin" };

  // private static String roles[] = null;
  private static String roles[] = DEFAULT_CONFIG_NEWUSER_ROLES;

  // private static String admin_roles[] = null;
  private static String admin_roles[] = DEFAULT_CONFIG_NEW_ADMINUSER_ROLES;

  /**
   * 指定したユーザーにデフォルトのPSMLを設定します。<br>
   * RunDataを使用する箇所、adminPageを追加する箇所をコメントアウトしました。<br>
   * 例外発生時にユーザーの削除は行わないようにしました。<br>
   * 
   * @param user
   * @throws JetspeedSecurityException
   * @see {@link ALUserManagement#addDefaultPSML(JetspeedUser, boolean)}
   */
  public static void addDefaultPSML(JetspeedUser user,
      boolean hasAdminCredential) throws JetspeedSecurityException {
    String orgId = Database.getDomainName();

    // grantRoles(user, hasAdminCredential);
    grantRoles(user, false);

    try {
      // JetspeedRunData rundata = getRunData();
      // if (rundata != null && Profiler.useRoleProfileMerging() == false) {
      // change start 受入テスト319
      BaseProfile profile = (BaseProfile) Profiler.createProfile();
      profile.setUser(user);
      profile.setMediaType("html");
      profile.setOrgName(orgId);
      // change start 受入テスト319
      profile.setMode("batch");
      // change end 受入テスト319
      // Profiler.createProfile(getRunData(), profile);
      Profiler.createProfile(null, profile);

      // if (hasAdminCredential) {
      // addAdminPage(user);
      // }
      // }
    } catch (Exception e) {
      logger.error("Failed to create profile for new user ", e);
      // ユーザーの削除は行わない。
      // removeUser(new UserNamePrincipal(user.getUserName()));
      throw new UserException("Failed to create profile for new user ", e);
    }
  }

  /**
   * ユーザーのロールを承認します<br>
   * コピークラスALBatchRoleUtilsのgrantRoleメソッドを呼ぶように変更しています。<br>
   * 
   * @param user
   * @param hasAdminCredential
   * @see {@link ALUserManagement#grantRoles(JetspeedUser, boolean)}
   */
  private static void grantRoles(JetspeedUser user, boolean hasAdminCredential) {
    String _roles[] = null;
    if (hasAdminCredential) {
      _roles = admin_roles;
    } else {
      _roles = roles;
    }

    for (int i = 0; i < _roles.length; i++) {
      try {
        // JetspeedSecurity.grantRole(user.getUserName(),
        // JetspeedSecurity.getRole(_roles[i]).getName());
        // コピークラスALBatchRoleUtilsのメソッドを呼ぶように変更しています。
        ALBatchRoleUtils.grantRole(user.getUserName(), JetspeedSecurity
          .getRole(_roles[i])
          .getName());
      } catch (Exception e) {
        logger.error("Could not grant role: "
          + _roles[i]
          + " to user "
          + user.getUserName(), e);
      }
    }
  }

}
