/*
 * Aipo is a groupware program developed by Aimluck,Inc.
 * http://aipostyle.com/
 * 
 * Copyright(C) 2009 avanza Co.,Ltd. All rights reserved.
 * http://www.avnz.co.jp/
 * 
 * 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.circulation;

import java.util.List;
import java.util.jar.Attributes;

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.commons.utils.ALDateUtil;
import com.aimluck.eip.cayenne.om.portlet.AvzTCirculationCategory;
import com.aimluck.eip.cayenne.om.portlet.AvzTCirculationRequest;
import com.aimluck.eip.cayenne.om.portlet.auto._AvzTCirculationRequest;
import com.aimluck.eip.cayenne.om.portlet.auto._AvzTCirculationRequestMap;
import com.aimluck.eip.circulation.util.CirculationUtils;
import com.aimluck.eip.common.ALAbstractSelectData;
import com.aimluck.eip.common.ALDBErrorException;
import com.aimluck.eip.common.ALData;
import com.aimluck.eip.common.ALPageNotFoundException;
import com.aimluck.eip.modules.actions.common.ALAction;
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.ALCommonUtils;
import com.aimluck.eip.util.ALEipUtils;

/**
 * Circulation検索データを管理するクラスです。 <BR>
 * 
 */
public class CirculationSelectData extends
    ALAbstractSelectData<AvzTCirculationRequest, AvzTCirculationRequest>
    implements ALData {

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

  /** サブメニュー（確認依頼） */
  public static final String SUBMENU_REQUESTED = "requested";

  /** サブメニュー（作成分） */
  public static final String SUBMENU_CREATED = "created";

  /** サブメニュー（確認依頼）のタブ（未確認） */
  public static final String TAB_UNCONFIRMED = "unconfirmed";

  /** サブメニュー（確認依頼）のタブ（確認済） */
  public static final String TAB_CONFIRMED = "confirmed";

  /** サブメニュー（確認依頼）のタブ（完了） */
  public static final String TAB_COMPLETED = "completed";

  /** サブメニュー（作成分）のタブ（未完了） */
  public static final String TAB_UNFINISHED = "unfinished";

  /** サブメニュー（作成分）のタブ（完了） */
  public static final String TAB_FINISHED = "finished";

  /** 現在選択されているサブメニュー */
  private String currentSubMenu;

  /** 現在選択されているタブ */
  private String currentTab;

  /** カテゴリ一覧 */
  private List<CirculationCategoryResultData> categoryList;

  /** ログインユーザーID */
  private long login_user_id;

  /**
   * 
   * @param action
   * @param rundata
   * @param context
   * @see com.aimluck.eip.common.ALAbstractSelectData#init(com.aimluck.eip.modules.actions.common.ALAction,
   *      org.apache.turbine.util.RunData, org.apache.velocity.context.Context)
   */
  @Override
  public void init(ALAction action, RunData rundata, Context context)
      throws ALPageNotFoundException, ALDBErrorException {

    super.init(action, rundata, context);

    String sort = ALEipUtils.getTemp(rundata, context, LIST_SORT_STR);
    if (sort == null || sort.equals("")) {
      ALEipUtils.setTemp(rundata, context, LIST_SORT_STR, ALEipUtils
        .getPortlet(rundata, context)
        .getPortletConfig()
        .getInitParameter("p2a-sort"));
      logger.debug("[avz_t_circulation_requestSelectData] Init Parameter. : "
        + ALEipUtils
          .getPortlet(rundata, context)
          .getPortletConfig()
          .getInitParameter("p2a-sort"));
    }

    String subMenuParam = rundata.getParameters().getString("submenu");
    currentSubMenu = ALEipUtils.getTemp(rundata, context, "submenu");
    if (subMenuParam == null && currentSubMenu == null) {
      ALEipUtils.setTemp(rundata, context, "submenu", SUBMENU_REQUESTED);
      currentSubMenu = SUBMENU_REQUESTED;
    } else if (subMenuParam != null) {
      ALEipUtils.setTemp(rundata, context, "submenu", subMenuParam);
      currentSubMenu = subMenuParam;
    }

    String tabParam = rundata.getParameters().getString("tab");
    currentTab = ALEipUtils.getTemp(rundata, context, "tab");
    if (tabParam == null && currentTab == null) {
      if (SUBMENU_REQUESTED.equals(currentSubMenu)) {
        tabParam = TAB_UNCONFIRMED;
      } else {
        tabParam = TAB_UNFINISHED;
      }
      ALEipUtils.setTemp(rundata, context, "tab", tabParam);
      currentTab = tabParam;
    } else if (tabParam != null) {
      ALEipUtils.setTemp(rundata, context, "tab", tabParam);
      currentTab = tabParam;
    }
    if (SUBMENU_REQUESTED.equals(currentSubMenu)) {
      if (TAB_UNFINISHED.equals(currentTab) || TAB_FINISHED.equals(currentTab)) {
        currentTab = TAB_UNCONFIRMED;
      }
    } else {
      if (TAB_UNCONFIRMED.equals(currentTab)
        || TAB_CONFIRMED.equals(currentTab)
        || TAB_COMPLETED.equals(currentTab)) {
        currentTab = TAB_UNFINISHED;
      }
    }

    login_user_id = ALEipUtils.getALEipUser(rundata).getUserId().getValue();

  }

  /**
   * 一覧データを取得します。 <BR>
   * 
   * @param rundata
   * @param context
   * @return
   * @see com.aimluck.eip.common.ALAbstractListData#selectData(org.apache.turbine.util.RunData,
   *      org.apache.velocity.context.Context)
   */
  // @Override
  // public List selectList(RunData rundata, Context context) {
  // try {
  // DataContext dataContext =
  // DatabaseOrmService.getInstance().getDataContext();
  //
  // SelectQuery query = getSelectQuery(rundata, context);
  // buildSelectQueryForListView(query);
  // buildSelectQueryForListViewSort(query, rundata, context);
  //
  // List list = dataContext.performQuery(query);
  // return buildPaginatedList(list);
  // } catch (Exception ex) {
  // logger.error("Exception", ex);
  // return null;
  // }
  // }
  /**
   * 一覧データを取得します。 <BR>
   * 
   * @param rundata
   * @param context
   * @return
   */
  @Override
  public ResultList<AvzTCirculationRequest> selectList(RunData rundata,
      Context context) {

    try {
      SelectQuery<AvzTCirculationRequest> query =
        getSelectQuery(rundata, context);
      buildSelectQueryForListView(query);
      buildSelectQueryForListViewSort(query, rundata, context);

      // 表示するカラムのみデータベースから取得する．
      ResultList<AvzTCirculationRequest> list = query.getResultList();
      return list;
    } catch (Exception ex) {
      logger.error("Exception", ex);
      return null;
    }
  }

  /**
   * 検索条件を設定した SelectQuery を返します。 <BR>
   * 
   * @param rundata
   * @param context
   * @return
   */
  private SelectQuery<AvzTCirculationRequest> getSelectQuery(RunData rundata,
      Context context) {
    // SelectQuery query = new SelectQuery(AvzTCirculationRequest.class);

    SelectQuery<AvzTCirculationRequest> query =
      Database.query(AvzTCirculationRequest.class);

    if (SUBMENU_REQUESTED.equals(currentSubMenu)) {
      // 確認依頼

      Expression exp01 =
        ExpressionFactory.matchExp(
          _AvzTCirculationRequest.AVZ_TCIRCULATION_REQUEST_MAP_ARRAY_PROPERTY
            + "."
            + _AvzTCirculationRequestMap.USER_ID_PROPERTY,
          login_user_id);
      query.setQualifier(exp01);

      if (TAB_UNCONFIRMED.equals(currentTab)) {
        Expression exp11 =
          ExpressionFactory.matchExp(
            _AvzTCirculationRequest.AVZ_TCIRCULATION_REQUEST_MAP_ARRAY_PROPERTY
              + "."
              + _AvzTCirculationRequestMap.STATUS_PROPERTY,
            CirculationUtils.DB_STATUS_REQUEST);
        query.andQualifier(exp11);

      } else if (TAB_CONFIRMED.equals(currentTab)) {
        Expression exp21 =
          ExpressionFactory.matchExp(
            _AvzTCirculationRequest.AVZ_TCIRCULATION_REQUEST_MAP_ARRAY_PROPERTY
              + "."
              + _AvzTCirculationRequestMap.STATUS_PROPERTY,
            CirculationUtils.DB_STATUS_CONFIRM);
        query.andQualifier(exp21);

        // add by motegi 20110113 start 完了したものも取得してしまうので追加
        Expression exp22 =
          ExpressionFactory.matchExp(
            _AvzTCirculationRequest.PROGRESS_PROPERTY,
            CirculationUtils.DB_PROGRESS_WAIT);
        query.andQualifier(exp22);
        // add end
      } else {
        Expression exp31 =
          ExpressionFactory.matchExp(
            _AvzTCirculationRequest.PROGRESS_PROPERTY,
            CirculationUtils.DB_PROGRESS_CONFIRM);
        query.andQualifier(exp31);
      }
    } else {
      // 作成分
      Expression exp1 =
        ExpressionFactory.matchExp(
          _AvzTCirculationRequest.USER_ID_PROPERTY,
          login_user_id);
      query.setQualifier(exp1);

      if (TAB_UNFINISHED.equals(currentTab)) {
        Expression exp41 =
          ExpressionFactory.matchExp(
            _AvzTCirculationRequest.PROGRESS_PROPERTY,
            CirculationUtils.DB_PROGRESS_WAIT);
        query.andQualifier(exp41);
      } else {
        Expression exp51 =
          ExpressionFactory.matchExp(
            _AvzTCirculationRequest.PROGRESS_PROPERTY,
            CirculationUtils.DB_PROGRESS_CONFIRM);
        query.andQualifier(exp51);
      }
    }

    return buildSelectQueryForFilter(query, rundata, context);
  }

  /**
   * ResultData に値を格納して返します。（一覧データ） <BR>
   * 
   * @param obj
   * @return
   * @see com.aimluck.eip.common.ALAbstractSelectData#getListData(java.lang.Object)
   */
  @Override
  protected Object getResultData(AvzTCirculationRequest obj) {
    try {
      AvzTCirculationRequest record = obj;
      CirculationResultData rd = new CirculationResultData();
      rd.initField();
      rd.setRequestId(record.getRequestId().intValue());
      rd.setRequestName(ALCommonUtils.compressString(
        record.getRequestName(),
        getStrLength()));
      rd.setCategoryId(record
        .getToAvzTCirculationCategory()
        .getCategoryId()
        .longValue());
      rd.setCategoryName(ALCommonUtils.compressString(record
        .getToAvzTCirculationCategory()
        .getCategoryName(), getStrLength()));
      rd.setUpdateDate(ALDateUtil.format(record.getUpdateDate(), "yyyy年M月d日"));
      rd.setCreateDate(CirculationUtils.translateDate(
        record.getCreateDate(),
        "yyyy年M月d日"));
      rd
        .setNote(ALCommonUtils.compressString(record.getNote(), getStrLength()));
      rd.setPriority(record.getPriority().intValue());
      rd.setPriorityImage(CirculationUtils.getPriorityImage(record
        .getPriority()
        .intValue()));
      rd.setPriorityString(CirculationUtils.getPriorityString(record
        .getPriority()
        .intValue()));

      rd.setProgressString(CirculationUtils
        .getCountOfConfirmedAvzTCirculationRequestMap(record)
        + "/"
        + CirculationUtils.getCountOfAvzTCirculationRequestMap(record));

      rd.setCreateUser(ALEipUtils.getUserFullName(record.getUserId()));

      rd.setOwnerId(record.getUserId());

      if (!CirculationUtils.isEmptyDate(record.getLimitDate())) {
        rd.setLimitDate(ALDateUtil.format(record.getLimitDate(), "yyyy年M月d日"));
      }
      // 期限状態を設定する．
      rd.setLimitState(CirculationUtils.getLimitState(record.getLimitDate()));

      return rd;
    } catch (Exception ex) {
      logger.error("Exception", ex);
      ex.printStackTrace();
      return null;
    }
  }

  /**
   * 詳細データを取得します。 <BR>
   * 
   * @param rundata
   * @param context
   * @return
   * @see com.aimluck.eip.common.ALAbstractSelectData#selectDetail(org.apache.turbine.util.RunData,
   *      org.apache.velocity.context.Context)
   */
  @Override
  public AvzTCirculationRequest selectDetail(RunData rundata, Context context)
      throws ALPageNotFoundException {
    try {
      AvzTCirculationRequest avz_t_circulation_request =
        CirculationUtils.getAvzTCirculationRequest(rundata, context);
      return avz_t_circulation_request;
    } catch (ALPageNotFoundException pageNotFound) {
      throw pageNotFound;
    }
  }

  /**
   * ResultData に値を格納して返します。（詳細データ） <BR>
   * 
   * @param obj
   * @return
   * @see com.aimluck.eip.common.ALAbstractSelectData#getResultDataDetail(java.lang.Object)
   */
  @Override
  protected Object getResultDataDetail(AvzTCirculationRequest obj) {
    return CirculationUtils.getResultDataDetail(obj, login_user_id);
  }

  /**
   * 
   * @param rundata
   * @param context
   */
  public void loadCategoryList(RunData rundata, Context context) {
    categoryList = CirculationUtils.loadCategoryList(rundata, context);
  }

  /**
   * 
   * @return
   */
  public List<CirculationCategoryResultData> getCategoryList() {
    return categoryList;
  }

  public long getLoginUser() {
    return login_user_id;
  }

  /**
   * @return
   * @see com.aimluck.eip.common.ALAbstractSelectData#getColumnMap()
   */
  @Override
  protected Attributes getColumnMap() {
    Attributes map = new Attributes();

    // Sort処理用
    map.putValue("request_name", AvzTCirculationRequest.REQUEST_NAME_PROPERTY);
    map.putValue("priority", AvzTCirculationRequest.PRIORITY_PROPERTY);
    map.putValue("create_date", AvzTCirculationRequest.LIMIT_DATE_PROPERTY);
    map.putValue("limit_date", AvzTCirculationRequest.LIMIT_DATE_PROPERTY);

    // Filter処理用
    map.putValue("category", AvzTCirculationCategory.CATEGORY_ID_PK_COLUMN);
    return map;
  }

  /**
   * 現在選択されているタブを取得します。 <BR>
   * 
   * @return
   */
  public String getCurrentTab() {
    return currentTab;
  }

  /**
   * 現在選択されているサブメニューを取得します。 <BR>
   * 
   * @return
   */
  public String getCurrentSubMenu() {
    return this.currentSubMenu;
  }

  /**
   * 
   * @param id
   * @return
   */
  public boolean isMatch(int id1, long id2) {
    return id1 == (int) id2;
  }

  /**
   * アクセス権限チェック用メソッド。<br />
   * アクセス権限の機能名を返します。
   * 
   * @return
   */
  @Override
  public String getAclPortletFeature() {
    return null;
  }
}
