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

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;

import org.apache.cayenne.exp.Expression;
import org.apache.cayenne.exp.ExpressionFactory;
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.AvzTWhereaboutsinformation;
import com.aimluck.eip.cayenne.om.portlet.EipMFacility;
import com.aimluck.eip.cayenne.om.portlet.EipTSchedule;
import com.aimluck.eip.cayenne.om.portlet.EipTScheduleMap;
import com.aimluck.eip.common.ALEipConstants;
import com.aimluck.eip.common.ALPageNotFoundException;
import com.aimluck.eip.orm.Database;
import com.aimluck.eip.orm.query.ResultList;
import com.aimluck.eip.orm.query.SelectQuery;
import com.aimluck.eip.util.ALEipUtils;

/**
 * WhereaboutsInformationのユーティリティクラスです。 <BR>
 * 
 */
public class WhereaboutsInformationUtils {

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

  /** <code>SCHEDULEMAP_TYPE_USER</code> ユーザ */
  public static final String SCHEDULEMAP_TYPE_USER = "U";

  /** <code>SCHEDULEMAP_TYPE_FACILITY</code> 設備 */
  public static final String SCHEDULEMAP_TYPE_FACILITY = "F";

  // 在席
  public static final String STATUS_PRESENCE = "P";

  // 離席
  public static final String STATUS_ABSENCE = "A";

  // 他者変更可
  public static final String PERMISSION_ON = "P";

  // 他者変更不可
  public static final String PERMISSION_OFF = "A";

  public static String getPlace(EipTSchedule schedule) {

    String place = schedule.getPlace();
    if (place.length() == 0) {

      SelectQuery<EipTScheduleMap> mapquery =
        Database.query(EipTScheduleMap.class);
      Expression mapexp1 =
        ExpressionFactory.matchExp(
          EipTScheduleMap.SCHEDULE_ID_PROPERTY,
          schedule.getScheduleId());
      mapquery.setQualifier(mapexp1);

      Expression mapexp3 =
        ExpressionFactory.matchExp(EipTScheduleMap.TYPE_PROPERTY, "F");
      mapquery.andQualifier(mapexp3);

      StringBuffer buf_facility = new StringBuffer();
      ResultList<EipTScheduleMap> schedulemaps = mapquery.getResultList();
      if (schedulemaps != null && schedulemaps.size() != 0) {
        for (EipTScheduleMap map : schedulemaps) {
          SelectQuery<EipMFacility> fquery = Database.query(EipMFacility.class);
          Expression fexp =
            ExpressionFactory.matchDbExp(
              EipMFacility.FACILITY_ID_PK_COLUMN,
              map.getUserId());
          fquery.setQualifier(fexp);

          ResultList<EipMFacility> aList = fquery.getResultList();
          if (aList != null && aList.size() != 0) {
            EipMFacility f = aList.get(0);
            String facility = f.getFacilityName();
            if (buf_facility.length() == 0) {
              buf_facility.append(facility);
            } else {
              buf_facility.append(" もしくは " + facility);
            }
          }
        }
      }

      if (buf_facility.length() == 0) {
        place = schedule.getName();
      } else {
        place = buf_facility.toString();
      }

    }
    return place;
  }

  public static String translateDate(Date date, String dateFormat) {
    if (date == null) {
      return "Unknown";
    }

    // 日付を表示形式に変換
    SimpleDateFormat sdf = new SimpleDateFormat(dateFormat);
    sdf.setTimeZone(TimeZone.getDefault());
    return sdf.format(date);
  }

  public static AvzTWhereaboutsinformation getAvzTwhereaboutsinformation(
      RunData rundata, Context context) throws ALPageNotFoundException {
    String whereaboutsinformationid =
      ALEipUtils.getTemp(rundata, context, ALEipConstants.ENTITY_ID);
    int user_id = ALEipUtils.getUserId(rundata);
    try {
      if (Integer.valueOf(user_id) == null) {
        logger.debug("[user_id] Empty ID...");
        return null;
      }

      SelectQuery<AvzTWhereaboutsinformation> query =
        Database.query(AvzTWhereaboutsinformation.class);
      Expression exp =
        ExpressionFactory.matchExp(
          AvzTWhereaboutsinformation.USER_ID_PROPERTY,
          user_id);
      query.setQualifier(exp);
      ResultList<AvzTWhereaboutsinformation> whereati = query.getResultList();

      if (whereati == null || whereati.size() == 0) {
        // 指定したwatiIDのレコードが見つからない場合
        logger.debug("[wati] Not found ID...");
        return null;
      }

      return whereati.get(0);

    } catch (Exception e) {
      logger.error("Exception", e);
      return null;
    }
  }

  public static AvzTWhereaboutsinformation getAvzTwhereaboutsinformationById(
      String userid) throws ALPageNotFoundException {
    try {
      if (userid == null || Integer.valueOf(userid) == null) {
        logger.debug("[Whereaboutsinformation] Empty ID...");
        return null;
      }

      SelectQuery<AvzTWhereaboutsinformation> query =
        Database.query(AvzTWhereaboutsinformation.class);
      Expression exp =
        ExpressionFactory.matchExp(
          AvzTWhereaboutsinformation.USER_ID_PROPERTY,
          userid);
      query.setQualifier(exp);
      ResultList<AvzTWhereaboutsinformation> wati = query.getResultList();

      if (wati == null || wati.size() == 0) {
        // 指定したwatiIDのレコードが見つからない場合
        logger.debug("[wati] Not found ID...");
        return null;
      }

      return wati.get(0);

    } catch (Exception e) {
      logger.error("Exception", e);
      return null;
    }
  }

}
