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

import java.util.ArrayList;
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.field.ALStringField;
import com.aimluck.commons.utils.ALDateUtil;
import com.aimluck.eip.cayenne.om.portlet.AvzTCabinetFile;
import com.aimluck.eip.cayenne.om.portlet.auto._AvzTCabinetFile;
import com.aimluck.eip.cayenne.om.portlet.auto._AvzTCabinetFolder;
import com.aimluck.eip.common.ALAbstractSelectData;
import com.aimluck.eip.common.ALDBErrorException;
import com.aimluck.eip.common.ALEipConstants;
import com.aimluck.eip.common.ALEipUser;
import com.aimluck.eip.common.ALPageNotFoundException;
import com.aimluck.eip.extcabinet.util.ExtCabinetUtils;
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.ALEipUtils;

/**
 * 文書管理のファイル検索用データ．
 * 
 */
public class ExtCabinetFileWordSelectData extends
    ALAbstractSelectData<AvzTCabinetFile, Object> {
  /** logger */
  private static final JetspeedLogger logger =
    JetspeedLogFactoryService.getLogger(ExtCabinetFileWordSelectData.class
      .getName());

  /** 検索ワード */
  private ALStringField searchWord;

  /** 検索結果件数 */
  // private final int searchSum = 0;
  /** 選択されたフォルダ情報 */
  private ExtFolderInfo selected_folderinfo = null;

  private List<ExtFolderInfo> folder_hierarchy_list;

  private RunData rundata;

  /**
   * @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, "folder_name");
    }

    int fid = ExtCabinetUtils.ROOT_FODLER_ID;
    String tmpfid =
      ALEipUtils.getTemp(
        rundata,
        context,
        ExtCabinetUtils.SESSION_KEY_FOLDER_ID);
    if (tmpfid != null && !"".equals(tmpfid)) {
      try {
        fid = Integer.parseInt(tmpfid);
      } catch (Exception e) {
        fid = ExtCabinetUtils.ROOT_FODLER_ID;
      }
    }
    folder_hierarchy_list =
      ExtCabinetUtils.getFolderList(ExtCabinetUtils.ROOT_PARENT_FODLER_ID);
    if (folder_hierarchy_list != null && folder_hierarchy_list.size() > 0) {
      int size = folder_hierarchy_list.size();
      for (int i = 0; i < size; i++) {
        ExtFolderInfo info = folder_hierarchy_list.get(i);
        if (info.getFolderId() == fid) {
          selected_folderinfo = info;
          break;
        }
      }
      if (selected_folderinfo == null) {
        selected_folderinfo = folder_hierarchy_list.get(0);
      }
    }
    this.rundata = rundata;
  }

  /**
   * 
   * @see com.aimluck.eip.common.ALAbstractSelectData#selectList(org.apache.turbine.util.RunData,
   *      org.apache.velocity.context.Context)
   */
  @Override
  protected ResultList<AvzTCabinetFile> selectList(RunData rundata,
      Context context) {
    // ページャからきた場合に検索ワードをセッションへ格納する
    if (!rundata.getParameters().containsKey(ALEipConstants.LIST_START)
      && !rundata.getParameters().containsKey(ALEipConstants.LIST_SORT)
      && rundata.getParameters().containsKey("sword")) {
      ALEipUtils.setTemp(rundata, context, "ExtCabinetFileWord", rundata
        .getParameters()
        .getString("sword"));
    }

    // 検索ワードの設定
    searchWord = new ALStringField();
    searchWord.setTrim(true);
    // セッションから値を取得する。
    // 検索ワード未指定時は空文字が入力される
    searchWord.setValue(ALEipUtils.getTemp(
      rundata,
      context,
      "ExtCabinetFileWord"));

    try {
      ExtCabinetUtils.setFolderVisible(
        folder_hierarchy_list,
        selected_folderinfo,
        rundata);

      SelectQuery<AvzTCabinetFile> query = getSelectQuery(rundata, context);
      // buildSelectQueryForListView(query);
      buildSelectQueryForListViewSort(query, rundata, context);

      List<AvzTCabinetFile> list = query.fetchList();

      // motegi start
      // 参照権限の無いファイルは一覧に表示しない。
      int size = list.size();
      List<AvzTCabinetFile> tmpList = new ArrayList<AvzTCabinetFile>();
      for (int i = 0; i < size; i++) {
        AvzTCabinetFile record = list.get(i);
        Integer file_id = record.getFileId();
        Integer user_id = record.getCreateUserId();
        List<String> aclHandle =
          ExtCabinetUtils.getFileAclHandle(rundata, file_id, user_id);
        if (ExtCabinetUtils.isReadable(aclHandle)) {
          tmpList.add(record);
        }
      }
      list = tmpList;
      // motegi end

      if (list != null) {
        // searchSum = list.size();
        List<AvzTCabinetFile> paged_list = buildPaginatedList(list);
        ResultList<AvzTCabinetFile> result = new ResultList<AvzTCabinetFile>();
        for (AvzTCabinetFile e : paged_list) {
          result.add(e);
        }
        return result;
      } else {
        logger.info("extcabinetFile search > result is null");
        return new ResultList<AvzTCabinetFile>();
      }
    } catch (Exception ex) {
      logger.error("Exception", ex);
      return null;
    }
  }

  /**
   * 未使用。
   * 
   * @see com.aimluck.eip.common.ALAbstractSelectData#selectDetail(org.apache.turbine.util.RunData,
   *      org.apache.velocity.context.Context)
   */
  @Override
  protected Object selectDetail(RunData rundata, Context context) {
    return null;
  }

  /**
   * @see com.aimluck.eip.common.ALAbstractSelectData#getResultData(java.lang.Object)
   */
  @Override
  protected Object getResultData(AvzTCabinetFile obj) {
    try {
      AvzTCabinetFile record = obj;

      ExtCabinetFileResultData rd = new ExtCabinetFileResultData();
      rd.initField();
      rd.setFileId(record.getFileId().longValue());
      rd.setFileTitle(record.getFileTitle());
      rd.setFileName(record.getFileName());
      rd.setFileSize(record.getFileSize().longValue());

      rd.setFolderId(record.getToAvzTCabinetFolder().getFolderId().intValue());
      rd.setFolderName((record.getToAvzTCabinetFolder()).getFolderName());
      String updateUserName = "";
      ALEipUser updateUser =
        ALEipUtils.getALEipUser(record.getUpdateUserId().intValue());
      if (updateUser != null) {
        updateUserName = updateUser.getAliasName().getValue();
      }
      rd.setUpdateUser(updateUserName);
      rd.setUpdateDate(ALDateUtil.format(record.getUpdateDate(), "yyyy年M月d日"));

      // motegi start
      Integer file_id = record.getFileId();
      Integer user_id = record.getCreateUserId();
      List<String> aclHandle =
        ExtCabinetUtils.getFileAclHandle(rundata, file_id, user_id);
      rd.setisReadable(ExtCabinetUtils.isReadable(aclHandle));
      rd.setisWritable(ExtCabinetUtils.isWritable(aclHandle));
      rd.setisDeletable(ExtCabinetUtils.isDeletable(aclHandle));
      // motegi end

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

  /**
   * 未使用。
   * 
   * @see com.aimluck.eip.common.ALAbstractSelectData#getResultDataDetail(java.lang.Object)
   */
  @Override
  protected Object getResultDataDetail(Object obj) {
    return null;
  }

  /**
   * @see com.aimluck.eip.common.ALAbstractSelectData#getColumnMap()
   */
  @Override
  protected Attributes getColumnMap() {
    Attributes map = new Attributes();
    map.putValue(
      "folder_name",
      _AvzTCabinetFile.TO_AVZ_TCABINET_FOLDER_PROPERTY
        + "."
        + _AvzTCabinetFolder.FOLDER_NAME_PROPERTY);
    map.putValue("file_title", _AvzTCabinetFile.FILE_TITLE_PROPERTY);
    map.putValue("file_name", _AvzTCabinetFile.FILE_NAME_PROPERTY);
    // map.putValue("update_user", TurbineUserConstants.LAST_NAME_KANA);
    map.putValue("update_date", _AvzTCabinetFile.UPDATE_DATE_PROPERTY);
    map.putValue("file_size", _AvzTCabinetFile.FILE_SIZE_PROPERTY);
    return map;
  }

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

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

    String word = searchWord.getValue();

    Expression exp11 =
      ExpressionFactory.likeExp(_AvzTCabinetFile.FILE_TITLE_PROPERTY, "%"
        + word
        + "%");
    Expression exp12 =
      ExpressionFactory.likeExp(_AvzTCabinetFile.FILE_NAME_PROPERTY, "%"
        + word
        + "%");
    Expression exp13 =
      ExpressionFactory.likeExp(_AvzTCabinetFile.NOTE_PROPERTY, "%"
        + word
        + "%");
    Expression exp14 =
      ExpressionFactory.inExp(
        _AvzTCabinetFile.FOLDER_ID_PROPERTY,
        ExtCabinetUtils.getAuthorizedVisibleFolderIds(rundata));

    query.setQualifier(exp11.orExp(exp12).orExp(exp13));
    query.andQualifier(exp14);

    return buildSelectQueryForFilter(query, rundata, context);
  }

  /**
   * 検索ワードを取得します。
   * 
   * @return
   */
  public ALStringField getSearchWord() {
    return searchWord;
  }

  // public int getSearchSum() {
  // return searchSum;
  // }

  public List<ExtFolderInfo> getFolderHierarchyList() {
    return folder_hierarchy_list;
  }

  public ExtFolderInfo getSelectedFolderInfo() {
    return selected_folderinfo;
  }

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