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

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.cayenne.DataRow;
import org.apache.cayenne.access.DataContext;
import org.apache.cayenne.query.SQLTemplate;
import org.apache.jetspeed.services.logging.JetspeedLogFactoryService;
import org.apache.jetspeed.services.logging.JetspeedLogger;
import org.apache.turbine.util.RunData;

import com.aimluck.eip.cayenne.om.security.TurbineUser;
import com.aimluck.eip.common.ALEipGroup;
import com.aimluck.eip.common.ALEipManager;
import com.aimluck.eip.common.ALEipPost;
import com.aimluck.eip.orm.DatabaseOrmService;
import com.aimluck.eip.user.beans.UserEmailLiteBean;
import com.aimluck.eip.user.beans.UserGroupLiteBean;
import com.aimluck.eip.user.beans.UserLiteBean;
import com.aimluck.eip.util.ALEipUtils;

/**
 * ユーザーのユーティリティクラスです。 <br />
 * 
 */
public class UserUtils {

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

  /**
   * 
   * @param rundata
   * @return
   */
  public static List getUserLiteBeansFromGroup(RunData rundata,
      String groupname, boolean includeLoginuser) {
    List list = new ArrayList();

    // SQLの作成
    StringBuffer statement = new StringBuffer();
    statement.append("SELECT DISTINCT ");
    statement
        .append("  B.USER_ID, B.LOGIN_NAME, B.FIRST_NAME, B.LAST_NAME, D.POSITION ");
    statement.append("FROM TURBINE_USER_GROUP_ROLE as A ");
    statement.append("LEFT JOIN TURBINE_USER as B ");
    statement.append("  on A.USER_ID = B.USER_ID ");
    statement.append("LEFT JOIN TURBINE_GROUP as C ");
    statement.append("  on A.GROUP_ID = C.GROUP_ID ");
    statement.append("LEFT JOIN EIP_M_USER_POSITION as D ");
    statement.append("  on A.USER_ID = D.USER_ID ");
    statement.append("WHERE B.USER_ID > 3 AND B.DISABLED = 'F'");
    if (!includeLoginuser) {
      // ログインユーザを含めない場合
      statement.append(" AND B.USER_ID <> " + ALEipUtils.getUserId(rundata));
    }
    statement.append(" AND C.GROUP_NAME = '").append(groupname).append("' ");
    statement.append("ORDER BY D.POSITION");
    String query = statement.toString();

    DataContext dataContext = DatabaseOrmService.getInstance().getDataContext();
    SQLTemplate rawSelect = new SQLTemplate(TurbineUser.class, query, true);
    rawSelect.setFetchingDataRows(true);
    List ulist = dataContext.performQuery(rawSelect);

    int recNum = ulist.size();

    UserLiteBean user;
    DataRow dataRow;
    // ユーザデータを作成し、返却リストへ格納
    for (int j = 0; j < recNum; j++) {
      dataRow = (DataRow) ulist.get(j);
      user = new UserLiteBean();
      user.initField();
      user.setUserId(((Integer) ALEipUtils.getObjFromDataRow(dataRow,
          TurbineUser.USER_ID_PK_COLUMN)).intValue());
      user.setName((String) ALEipUtils.getObjFromDataRow(dataRow,
          TurbineUser.LOGIN_NAME_COLUMN));
      user.setAliasName((String) ALEipUtils.getObjFromDataRow(dataRow,
          TurbineUser.FIRST_NAME_COLUMN), (String) ALEipUtils
          .getObjFromDataRow(dataRow, TurbineUser.LAST_NAME_COLUMN));
      list.add(user);
    }
    return list;
  }

  /**
   * 
   * @param rundata
   * @return
   */
  public static List getUserEmailLiteBeansFromGroup(RunData rundata,
      String groupname, boolean includeLoginuser) {
    List list = new ArrayList();

    // SQLの作成
    StringBuffer statement = new StringBuffer();
    statement.append("SELECT DISTINCT ");
    statement
        .append("  B.USER_ID, B.LOGIN_NAME, B.FIRST_NAME, B.LAST_NAME, B.EMAIL, D.POSITION ");
    statement.append("FROM TURBINE_USER_GROUP_ROLE as A ");
    statement.append("LEFT JOIN TURBINE_USER as B ");
    statement.append("  on A.USER_ID = B.USER_ID ");
    statement.append("LEFT JOIN TURBINE_GROUP as C ");
    statement.append("  on A.GROUP_ID = C.GROUP_ID ");
    statement.append("LEFT JOIN EIP_M_USER_POSITION as D ");
    statement.append("  on A.USER_ID = D.USER_ID ");
    statement.append("WHERE B.USER_ID > 3 AND B.DISABLED = 'F'");
    if (!includeLoginuser) {
      // ログインユーザを含めない場合
      statement.append(" AND B.USER_ID <> " + ALEipUtils.getUserId(rundata));
    }
    statement.append(" AND C.GROUP_NAME = '").append(groupname).append("' ");
    statement.append("ORDER BY D.POSITION");
    String query = statement.toString();

    DataContext dataContext = DatabaseOrmService.getInstance().getDataContext();
    SQLTemplate rawSelect = new SQLTemplate(TurbineUser.class, query, true);
    rawSelect.setFetchingDataRows(true);
    List ulist = dataContext.performQuery(rawSelect);

    int recNum = ulist.size();

    UserEmailLiteBean user;
    DataRow dataRow;
    // ユーザデータを作成し、返却リストへ格納
    for (int j = 0; j < recNum; j++) {
      dataRow = (DataRow) ulist.get(j);
      user = new UserEmailLiteBean();
      user.initField();
      user.setUserId(((Integer) ALEipUtils.getObjFromDataRow(dataRow,
          TurbineUser.USER_ID_PK_COLUMN)).intValue());
      user.setName((String) ALEipUtils.getObjFromDataRow(dataRow,
          TurbineUser.LOGIN_NAME_COLUMN));
      user.setAliasName((String) ALEipUtils.getObjFromDataRow(dataRow,
          TurbineUser.FIRST_NAME_COLUMN), (String) ALEipUtils
          .getObjFromDataRow(dataRow, TurbineUser.LAST_NAME_COLUMN));
      user.setEmail((String) ALEipUtils.getObjFromDataRow(dataRow,
          TurbineUser.EMAIL_COLUMN));
      list.add(user);
    }
    return list;
  }

  /**
   * 
   * @param rundata
   * @return
   */
  public static List getUserGroupLiteBeans(RunData rundata, boolean isMygroup,
      boolean isPost) {
    List list = new ArrayList();
    UserGroupLiteBean bean;
    try {
      if (isMygroup) {
        List mygroup = ALEipUtils.getMyGroups(rundata);
        int size1 = mygroup.size();
        for (int i = 0; i < size1; i++) {
          ALEipGroup group = (ALEipGroup) mygroup.get(i);
          bean = new UserGroupLiteBean();
          bean.initField();
          bean.setGroupId(group.getName().getValue());
          bean.setName(group.getAliasName().getValue());
          list.add(bean);
        }
      }
      if (isPost) {
        Map postmap = ALEipManager.getInstance().getPostMap();
        for (Iterator i = postmap.values().iterator(); i.hasNext();) {
          ALEipPost post = (ALEipPost) i.next();
          bean = new UserGroupLiteBean();
          bean.initField();
          bean.setGroupId(post.getGroupName().getValue());
          bean.setName(post.getPostName().getValue());
          list.add(bean);
        }
      }
    } catch (Exception e) {
      logger.error("[UserUtils]", e);
    }
    return list;
  }

}
