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

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
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.EipMFacility;
import com.aimluck.eip.cayenne.om.portlet.ImwMPaidHolidayList;
import com.aimluck.eip.common.ALEipConstants;
import com.aimluck.eip.orm.DatabaseOrmService;
import com.aimluck.eip.paidholidaylist.PaidHolidayListResultData;
import com.aimluck.eip.util.ALEipUtils;

/**
 * 有給付与のユーティリティクラスです。 <BR>
 *
 */
public class PaidHolidayListUtils {

	
/*delete 趙丹2010/01/26 Start----  */	
//  /** logger */
//  private static final JetspeedLogger logger = JetspeedLogFactoryService
//      .getLogger(PaidHolidayListUtils.class.getName());
//
//  /**
//   * 有給付与オブジェクトモデルを取得します。 <BR>
//   *
//   * @param rundata
//   * @param context
//   * @return
//   */
//  public static EipMFacility getEipMFacility(RunData rundata, Context context) {
//    String facilityid = ALEipUtils.getTemp(rundata, context,
//        ALEipConstants.ENTITY_ID);
//    try {
//      if (facilityid == null || Integer.valueOf(facilityid) == null) {
//        // PaidHolidayList IDが空の場合
//        logger.debug("[Facility] Empty ID...");
//        return null;
//      }
//
//      DataContext dataContext = DatabaseOrmService.getInstance()
//          .getDataContext();
//      Expression exp = ExpressionFactory.matchDbExp(
//          EipMFacility.FACILITY_ID_PK_COLUMN, facilityid);
//      SelectQuery query = new SelectQuery(EipMFacility.class, exp);
//      List paidholidaylist = dataContext.performQuery(query);
//      if (paidholidaylist == null || paidholidaylist.size() == 0) {
//        // 指定したPaidHolidayList IDのレコードが見つからない場合
//        logger.debug("[PaidHolidayList] Not found ID...");
//        return null;
//      }
//      return ((EipMFacility) paidholidaylist.get(0));
//    } catch (Exception ex) {
//      logger.error("Exception", ex);
//      return null;
//    }
//  }
//
//  /**
//   *
//   * @param rundata
//   * @param context
//   */
//  public static List getFacilityAllList() {
//    List facilityAllList = new ArrayList();
//
//    try {
//      DataContext dataContext = DatabaseOrmService.getInstance()
//          .getDataContext();
//      SelectQuery query = new SelectQuery(EipMFacility.class);
//      List aList = dataContext.performQuery(query);
//
//      int size = aList.size();
//      for (int i = 0; i < size; i++) {
//        EipMFacility record = (EipMFacility) aList.get(i);
//        PaidHolidayListResultData rd = new PaidHolidayListResultData();
//        rd.initField();
//        rd.setFacilityId(record.getFacilityId().longValue());
//        rd.setFacilityName(record.getFacilityName());
//        facilityAllList.add(rd);
//      }
//    } catch (Exception ex) {
//      logger.error("Exception", ex);
//    }
//    return facilityAllList;
//  }
//
//  public static List getFacilityList(String groupname) {
//    List list = new ArrayList();
//
//    // SQLの作成
//    StringBuffer statement = new StringBuffer();
//    statement.append("SELECT DISTINCT ");
//    statement.append("  B.FACILITY_ID, B.FACILITY_NAME ");
//    statement.append("FROM EIP_FACILITY_GROUP as A ");
//    statement.append("LEFT JOIN EIP_M_FACILITY as B ");
//    statement.append("  on A.FACILITY_ID = B.FACILITY_ID ");
//    statement.append("LEFT JOIN TURBINE_GROUP as C ");
//    statement.append("  on A.GROUP_ID = C.GROUP_ID ");
//    statement.append("WHERE C.GROUP_NAME = '").append(groupname).append("'");
//    String query = statement.toString();
//
//    try {
//      DataContext dataContext = DatabaseOrmService.getInstance()
//          .getDataContext();
//      SQLTemplate rawSelect = new SQLTemplate(EipMFacility.class, query, true);
//      rawSelect.setFetchingDataRows(true);
//      List flist = dataContext.performQuery(rawSelect);
//      int recNum = flist.size();
//
//      PaidHolidayListResultData frd;
//      DataRow dataRow;
//      // ユーザデータを作成し、返却リストへ格納
//      for (int j = 0; j < recNum; j++) {
//        dataRow = (DataRow) flist.get(j);
//        frd = new PaidHolidayListResultData();
//        frd.initField();
//        frd.setFacilityId(((Integer) ALEipUtils.getObjFromDataRow(dataRow,
//            EipMFacility.FACILITY_ID_PK_COLUMN)).intValue());
//        frd.setFacilityName((String) ALEipUtils.getObjFromDataRow(dataRow,
//            EipMFacility.FACILITY_NAME_COLUMN));
//        list.add(frd);
//      }
//    } catch (Exception ex) {
//      logger.error("[Exception]", ex);
//    }
//
//    return list;
//  }
//
//  public static List getFacilityIds(String groupname) {
//    List list = new ArrayList();
//
//    // SQLの作成
//    StringBuffer statement = new StringBuffer();
//    statement.append("SELECT DISTINCT ");
//    statement.append("  B.FACILITY_ID ");
//    statement.append("FROM EIP_FACILITY_GROUP as A ");
//    statement.append("LEFT JOIN EIP_M_FACILITY as B ");
//    statement.append("  on A.FACILITY_ID = B.FACILITY_ID ");
//    statement.append("LEFT JOIN TURBINE_GROUP as C ");
//    statement.append("  on A.GROUP_ID = C.GROUP_ID ");
//    statement.append("WHERE C.GROUP_NAME = '").append(groupname).append("'");
//    String query = statement.toString();
//
//    try {
//      DataContext dataContext = DatabaseOrmService.getInstance()
//          .getDataContext();
//      SQLTemplate rawSelect = new SQLTemplate(EipMFacility.class, query, true);
//      rawSelect.setFetchingDataRows(true);
//      List flist = dataContext.performQuery(rawSelect);
//      int recNum = flist.size();
//
//      DataRow dataRow;
//      // ユーザデータを作成し、返却リストへ格納
//      for (int j = 0; j < recNum; j++) {
//        dataRow = (DataRow) flist.get(j);
//        list.add((Integer) ALEipUtils.getObjFromDataRow(dataRow,
//            EipMFacility.FACILITY_ID_PK_COLUMN));
//      }
//    } catch (Exception ex) {
//      logger.error("[Exception]", ex);
//    }
//
//    return list;
//  }
//
//  public static List getPaidHolidayListFromSelectQuery(SelectQuery query) {
//    List list = new ArrayList();
//    try {
//      DataContext dataContext = DatabaseOrmService.getInstance()
//          .getDataContext();
//      List aList = dataContext.performQuery(query);
//
//      int size = aList.size();
//
//      for (int i = 0; i < size; i++) {
//        EipMFacility record = (EipMFacility) aList.get(i);
//        PaidHolidayListResultData rd = new PaidHolidayListResultData();
//        rd.initField();
//        rd.setFacilityName(record.getFacilityName());
//        rd.setFacilityId(record.getFacilityId().longValue());
//        list.add(rd);
//      }
//    } catch (Exception ex) {
//      logger.error("[Exception]", ex);
//    }
//    Collections.sort(list, new Comparator<PaidHolidayListResultData>(){
//      public int compare(PaidHolidayListResultData str1, PaidHolidayListResultData str2) {
//        return str1.getStringFacilityName().compareTo(str2.getStringFacilityName());
//      }
//    });
//    return list;
//  }
//
//  /**
//   * 第一引数のリストに，第二引数で指定したユーザ ID が含まれているかを検証する．
//   *
//   * @param memberIdList
//   * @param memberId
//   * @return
//   */
//  public static boolean isContains(List facilityrList, PaidHolidayListResultData rd) {
//    int size = facilityrList.size();
//    long fid = rd.getFacilityId().getValue();
//    PaidHolidayListResultData facility = null;
//    for (int i = 0; i < size; i++) {
//      facility = (PaidHolidayListResultData) facilityrList.get(i);
//      if (facility.getFacilityId().getValue() == fid) {
//        return true;
//      }
//    }
//    return false;
//  }
/*delete 趙丹2011/01/26 End----  */	
	
	
/*add 趙丹 2010/01/26 Start----  */
	 /** logger */
	  private static final JetspeedLogger logger = JetspeedLogFactoryService
	      .getLogger(PaidHolidayListUtils.class.getName());

	  /**
	   * 有給付与オブジェクトモデルを取得します。 <BR>
	   *
	   * @param rundata
	   * @param context
	   * @return
	   */
	  
	  public static ImwMPaidHolidayList getImwMPaidHolidayList(RunData rundata, Context context) {
	    String paidholidaylistid = ALEipUtils.getTemp(rundata, context,
	        ALEipConstants.ENTITY_ID);
	    try {
	      if (paidholidaylistid == null || Integer.valueOf(paidholidaylistid) == null) {
	        // PaidHolidayList IDが空の場合
	        logger.debug("[PaidHolidayList] Empty ID...");
	        return null;
	      }

	      DataContext dataContext = DatabaseOrmService.getInstance()
	          .getDataContext();
	      Expression exp = ExpressionFactory.matchDbExp(
	    	  ImwMPaidHolidayList.PAID_HOLIDAY_LIST_ID_PK_COLUMN,paidholidaylistid);
	      SelectQuery query = new SelectQuery(ImwMPaidHolidayList.class, exp);
	      List paidholidaylist = dataContext.performQuery(query);
	      if (paidholidaylist == null || paidholidaylist.size() == 0) {
	        // 指定したPaidHolidayList IDのレコードが見つからない場合
	        logger.debug("[PaidHolidayList] Not found ID...");
	        return null;
	      }
	      return ((ImwMPaidHolidayList) paidholidaylist.get(0));
	    } catch (Exception ex) {
	      logger.error("Exception", ex);
	      return null;
	    }
	  }

	  /**
	   *
	   * @param rundata
	   * @param context
	   */
	  public static List getPaidHolidayListAllList() {
	    List paidholidaylistAllList = new ArrayList();

	    try {
	      DataContext dataContext = DatabaseOrmService.getInstance()
	          .getDataContext();
	      SelectQuery query = new SelectQuery(ImwMPaidHolidayList.class);
	      List aList = dataContext.performQuery(query);

	      int size = aList.size();
	      for (int i = 0; i < size; i++) {
	    	ImwMPaidHolidayList record = (ImwMPaidHolidayList) aList.get(i);
	        PaidHolidayListResultData rd = new PaidHolidayListResultData();
	        rd.initField();
	        rd.setPaidHolidayListId(record.getPaidHolidayListId());
	        rd.setServeYears(record.getServeYears());
	        rd.setPaidHolidayDays(record.getPaidHolidayDays());
	        paidholidaylistAllList.add(rd);
	      }
	    } catch (Exception ex) {
	      logger.error("Exception", ex);
	    }
	    return paidholidaylistAllList;
	  }

	  public static List getPaidHolidayListList(String groupname) {
	    List list = new ArrayList();

	    // SQLの作成
	    StringBuffer statement = new StringBuffer();
	    statement.append("SELECT DISTINCT ");
	    statement.append("  A.PAID_HOLIDAY_LIST_ID,A.SERVE_YEARS,A.PAID_HOLIDAY_DAYS ");
	    statement.append("FROM IMW_M_PAID_HOLIDAY_LIST as A ORDER BY A.SERVE_YEARS").append(groupname).append("'");
	    String query = statement.toString();

	    try {
	      DataContext dataContext = DatabaseOrmService.getInstance()
	          .getDataContext();
	      SQLTemplate rawSelect = new SQLTemplate(ImwMPaidHolidayList.class, query, true);
	      rawSelect.setFetchingDataRows(true);
	      List flist = dataContext.performQuery(rawSelect);
	      int recNum = flist.size();

	      PaidHolidayListResultData frd;
	      DataRow dataRow;
	      // ユーザデータを作成し、返却リストへ格納
	      for (int j = 0; j < recNum; j++) {
	        dataRow = (DataRow) flist.get(j);
	        frd = new PaidHolidayListResultData();
	        frd.initField();
	        frd.setPaidHolidayListId(((Integer)ALEipUtils.getObjFromDataRow(dataRow, ImwMPaidHolidayList.PAID_HOLIDAY_LIST_ID_PK_COLUMN)));
	        frd.setServeYears(((Integer)ALEipUtils.getObjFromDataRow(dataRow, ImwMPaidHolidayList.SERVE_YEARS_PROPERTY)));
	        frd.setServeYears(((Integer)ALEipUtils.getObjFromDataRow(dataRow, ImwMPaidHolidayList.PAID_HOLIDAY_DAYS_PROPERTY)));
	        list.add(frd);
	      }
	    } catch (Exception ex) {
	      logger.error("[Exception]", ex);
	    }

	    return list;
	  }

	  public static List getPaidHolidayListIds(String groupname) {
	    List list = new ArrayList();

	    // SQLの作成
	    StringBuffer statement = new StringBuffer();
	    statement.append("SELECT DISTINCT ");
	    statement.append("  A.PAID_HOLIDAY_LIST_ID,A.SERVE_YEARS,A.PAID_HOLIDAY_DAYS ");
	    statement.append("FROM IMW_M_PAID_HOLIDAY_LIST as A ORDER BY A.SERVE_YEARS").append(groupname).append("'");
	    String query = statement.toString();

	    try {
	      DataContext dataContext = DatabaseOrmService.getInstance()
	          .getDataContext();
	      SQLTemplate rawSelect = new SQLTemplate(ImwMPaidHolidayList.class, query, true);
	      rawSelect.setFetchingDataRows(true);
	      List flist = dataContext.performQuery(rawSelect);
	      int recNum = flist.size();

	      DataRow dataRow;
	      // ユーザデータを作成し、返却リストへ格納
	      for (int j = 0; j < recNum; j++) {
	        dataRow = (DataRow) flist.get(j);
	        list.add((Integer) ALEipUtils.getObjFromDataRow(dataRow,
	        ImwMPaidHolidayList.PAID_HOLIDAY_LIST_ID_PK_COLUMN));
	      }
	    } catch (Exception ex) {
	      logger.error("[Exception]", ex);
	    }

	    return list;
	  }

	  public static List getPaidHolidayListFromSelectQuery(SelectQuery query) {
	    List list = new ArrayList();
	    try {
	      DataContext dataContext = DatabaseOrmService.getInstance()
	          .getDataContext();
	      List aList = dataContext.performQuery(query);

	      int size = aList.size();

	      for (int i = 0; i < size; i++) {
	    	ImwMPaidHolidayList record = (ImwMPaidHolidayList) aList.get(i);
	        PaidHolidayListResultData rd = new PaidHolidayListResultData();
	        rd.initField();
	        rd.setPaidHolidayListId(record.getPaidHolidayListId());
	        rd.setServeYears(record.getServeYears());
	        rd.setPaidHolidayDays(record.getPaidHolidayDays());
	        list.add(rd);
	      }
	    } catch (Exception ex) {
	      logger.error("[Exception]", ex);
	    }
	    Collections.sort(list, new Comparator<PaidHolidayListResultData>(){
	      public int compare(PaidHolidayListResultData str1, PaidHolidayListResultData str2) {
	        return str1.getStringServeYears().compareTo(str2.getStringServeYears());
	        
	      }
	    });
	    return list;
	  }

	  /**
	   * 第一引数のリストに，第二引数で指定したユーザ ID が含まれているかを検証する．
	   *
	   * @param memberIdList
	   * @param memberId
	   * @return
	   */
	  public static boolean isContains(List paidholidaylistList, PaidHolidayListResultData rd) {
	    int size = paidholidaylistList.size();
	    long fid = rd.getPaidHolidayListId().getValue();
	    PaidHolidayListResultData paidholidaylist = null;
	    for (int i = 0; i < size; i++) {
	    	paidholidaylist = (PaidHolidayListResultData) paidholidaylistList.get(i);
	      if (paidholidaylist.getPaidHolidayListId().getValue() == fid) {
	        return true;
	      }
	    }
	    return false;
	  }
/*add 趙丹 2010/01/26 End----  */
}
