/*
 * 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.office.util;

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

import org.apache.cayenne.DataRow;
import org.apache.cayenne.access.DataContext;
import org.apache.cayenne.exp.Expression;
import org.apache.cayenne.exp.ExpressionFactory;
import org.apache.cayenne.query.SQLTemplate;
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.ImwTOffice;
import com.aimluck.eip.cayenne.om.security.TurbineUser;
import com.aimluck.eip.common.ALEipConstants;
import com.aimluck.eip.common.ALImwTOffice;
import com.aimluck.eip.orm.DatabaseOrmService;
import com.aimluck.eip.util.ALEipUtils;

/**
 * 勤務先のユーティリティクラスです
 */
public class OfficeUtils {

  /** logger */
  private static final JetspeedLogger logger = JetspeedLogFactoryService
      .getLogger(OfficeUtils.class.getName());
  
  /**
   * セッションに格納されているIDを用いて、勤務先情報を取得します。
   *
   * @param rundata
   * @param context
   * @return
   */
  public static ImwTOffice getImwTOffice(RunData rundata, Context context) {
    ImwTOffice result = null;
    String id = ALEipUtils.getTemp(rundata, context, ALEipConstants.ENTITY_ID);
    try {
      if (id == null || Integer.valueOf(id) == null) {
        logger.debug("Empty ID...");
        return result;
      }

      DataContext dataContext = DatabaseOrmService.getInstance()
          .getDataContext();
      Expression exp = ExpressionFactory.matchDbExp(ImwTOffice.OFFICE_ID_PK_COLUMN,
          Integer.valueOf(id));
      SelectQuery query = new SelectQuery(ImwTOffice.class, exp);
      List list = dataContext.performQuery(query);
      if (list == null || list.size() == 0) {
        logger.debug("Not found ID...");
        return result;
      }
      result = (ImwTOffice) list.get(0);
    } catch (Exception ex) {
      logger.error("Exception", ex);
    }
    return result;
  }
  
  /**
   * 指定されたグループに所属するユーザーを取得します。
   * 
   * @param officename
   *            グループ名
   * @return ALEipUser の List
   */
  public static List getOfficeUsers(String officename) {
    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,C.OFFICE_ID ");
    statement.append("FROM IMW_T_OFFICE_CALENDAR_MAP as A ");
    statement.append("LEFT JOIN TURBINE_USER as B ");
    statement.append("  on A.USER_ID = B.USER_ID ");
    statement.append("LEFT JOIN IMW_T_OFFICE as C ");
    statement.append("  on A.OFFICE_ID = C.OFFICE_ID ");
    statement.append("WHERE B.USER_ID > 3 AND B.DISABLED = 'F'");
    statement.append(" AND C.OFFICE_NAME = '").append(officename).append("' ");
    statement.append("ORDER BY C.OFFICE_ID");
    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();

    ALImwTOffice office;
    DataRow dataRow;
    for (int j = 0; j < recNum; j++) {
      dataRow = (DataRow) ulist.get(j);
      office = new ALImwTOffice();
      office.initField();
      office.setUserId(((Integer) ALEipUtils.getObjFromDataRow(dataRow, 
          TurbineUser.USER_ID_PK_COLUMN)).intValue());
      office.setAliasName((String) ALEipUtils.getObjFromDataRow(dataRow, 
          TurbineUser.FIRST_NAME_COLUMN), (String) ALEipUtils
          .getObjFromDataRow(dataRow, TurbineUser.LAST_NAME_COLUMN));
      list.add(office);
    }
    return list;
  }
}
