/*
 * 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.Iterator;
import java.util.List;
import java.util.jar.Attributes;

import org.apache.jetspeed.portal.portlets.VelocityPortlet;
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.AvzTCabinetFile;
import com.aimluck.eip.cayenne.om.portlet.AvzTCabinetFolder;
import com.aimluck.eip.cayenne.om.portlet.auto._AvzTCabinetFile;
import com.aimluck.eip.common.ALAbstractSelectData;
import com.aimluck.eip.common.ALDBErrorException;
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;

/**
 * 文書管理のファイル検索データを管理するためのクラスです。 <br />
 */
public class ExtCabinetSelectData extends
    ALAbstractSelectData<AvzTCabinetFile, AvzTCabinetFile> {

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

  /** 選択されたフォルダ情報 */
  private ExtFolderInfo selected_folderinfo = null;

  private List<ExtFolderInfo> folder_hierarchy_list;

  /** ノーマル画面の表示かどうか */
  private boolean isNormalContext = false;

  private RunData rundata;

  /** ファイルの追加権限 */
  private boolean isFileCreatable = true;

  /** フォルダの追加権限 */
  private boolean isFolderCreatable = true;

  private boolean isReadable = true;

  private boolean isWritable = true;

  private boolean isDeletable = true;

  public void setIsNormalContext(boolean flg) {
    isNormalContext = flg;
  }

  /**
   * 
   * @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("p1c-sort"));
    }

    int fid = ExtCabinetUtils.ROOT_FODLER_ID;
    if (isNormalContext) {
      // 通常画面
      // フォルダの初期値を取得する
      String filter = ALEipUtils.getTemp(rundata, context, LIST_FILTER_STR);
      if (filter == null || filter.equals("")) {
        VelocityPortlet portlet = ALEipUtils.getPortlet(rundata, context);
        String folderId =
          portlet.getPortletConfig().getInitParameter("p3a-folder");
        if (folderId != null) {
          ALEipUtils.setTemp(rundata, context, LIST_FILTER_STR, folderId);
          ALEipUtils.setTemp(rundata, context, LIST_FILTER_TYPE_STR, "folder");
        }
      }
      fid =
        Integer.parseInt(ALEipUtils.getTemp(rundata, context, LIST_FILTER_STR));
    } else {
      // 最大化画面
      // セッションから処理対象のフォルダーIDを取得
      String tmpfid =
        ALEipUtils.getTemp(
          rundata,
          context,
          ExtCabinetUtils.SESSION_KEY_FOLDER_ID);
      if (tmpfid != null && !"".equals(tmpfid)) {
        fid = Integer.parseInt(tmpfid);
      }

      // 自ポートレットからのリクエストであれば、パラメータを展開しセッションに保存する。
      if (ALEipUtils.isMatch(rundata, context)) {
        // リクエストにフォルダーIDがあればセッションの値を変更します。
        if (rundata.getParameters().containsKey(
          ExtCabinetUtils.REQUEST_KEY_FOLDER_ID)) {
          // リクエストにフォルダーIDがあればこちらを設定します。
          fid =
            Integer.parseInt(rundata.getParameters().getString(
              ExtCabinetUtils.REQUEST_KEY_FOLDER_ID));
        }
      }

      /** フォルダ権限のチェック */
      AvzTCabinetFolder folder = ExtCabinetUtils.getFolderByPK(fid);
      if (folder == null) {
        // 指定されているフォルダーIDがDBに無い場合はルートフォルダー
        folder = ExtCabinetUtils.getFolderByPK(ExtCabinetUtils.ROOT_FODLER_ID);
        fid = ExtCabinetUtils.ROOT_FODLER_ID;
      }

      List<String> aclHandle =
        ExtCabinetUtils.getFolderAclHandle(rundata, fid, folder
          .getCreateUserId());
      isFileCreatable = ExtCabinetUtils.isFileCreatable(aclHandle);
      isFolderCreatable = ExtCabinetUtils.isFolderCreatable(aclHandle);
      isReadable = ExtCabinetUtils.isReadable(aclHandle);
      isWritable = ExtCabinetUtils.isWritable(aclHandle);
      isDeletable = ExtCabinetUtils.isDeletable(aclHandle);

      ALEipUtils.setTemp(
        rundata,
        context,
        ExtCabinetUtils.SESSION_KEY_FOLDER_ID,
        String.valueOf(fid));
      ALEipUtils
        .setTemp(rundata, context, LIST_FILTER_STR, String.valueOf(fid));
      ALEipUtils.setTemp(rundata, context, LIST_FILTER_TYPE_STR, "folder");
    }

    // 表示用のフォルダーリストを取得して、選択されているフォルダーもあわせて取得
    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) throws ALPageNotFoundException, ALDBErrorException {
    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();

      // 参照権限の無いファイルは一覧に表示しない。
      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;
      if (list != null) {
        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;
    }
  }

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

  /**
   * @see com.aimluck.eip.common.ALAbstractSelectData#selectDetail(org.apache.turbine.util.RunData,
   *      org.apache.velocity.context.Context)
   */
  @Override
  protected AvzTCabinetFile selectDetail(RunData rundata, Context context)
      throws ALPageNotFoundException, ALDBErrorException {
    return ExtCabinetUtils.getAvzTCabinetFile(rundata, context);
  }

  /**
   * @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日"));

      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));

      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(AvzTCabinetFile obj)
      throws ALPageNotFoundException, ALDBErrorException {
    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.setPosition(ExtCabinetUtils.getFolderPosition(
        folder_hierarchy_list,
        record.getFolderId().intValue()));
      rd.setNote(record.getNote());

      String createUserName = "";
      ALEipUser createUser =
        ALEipUtils.getALEipUser(record.getCreateUserId().intValue());
      if (createUser != null) {
        createUserName = createUser.getAliasName().getValue();
      }
      rd.setCreateUser(createUserName);
      rd.setCreateDate(ALDateUtil.format(record.getCreateDate(), "yyyy年M月d日"));
      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日"));

      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));

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

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

  public List<ExtFolderInfo> getVisibleFolderHierarchyList() {

    // 権限的に参照可能なフォルダーのみに絞る
    ExtCabinetUtils.setFolderAuthorizedVisible(folder_hierarchy_list, rundata);
    Iterator<ExtFolderInfo> it = folder_hierarchy_list.iterator();
    List<ExtFolderInfo> tmpList = new ArrayList<ExtFolderInfo>();
    while (it.hasNext()) {
      ExtFolderInfo folderinfo = it.next();
      if (!folderinfo.isAuthorizedVisible()) {
        continue;
      }

      StringBuffer nbsps = new StringBuffer();
      int len = folderinfo.getHierarchyIndex();
      for (int i = 0; i < len; i++) {
        nbsps.append("―");
      }

      folderinfo.setFolderNameDisplay(nbsps.toString()
        + folderinfo.getFolderName());

      tmpList.add(folderinfo);
    }
    return tmpList;
  }

  public ExtFolderInfo getSelectedFolderInfo() {
    return selected_folderinfo;
  }

  /**
   * @see com.aimluck.eip.common.ALAbstractSelectData#getColumnMap()
   */
  @Override
  protected Attributes getColumnMap() {
    Attributes map = new Attributes();
    map.putValue("file_title", _AvzTCabinetFile.FILE_TITLE_PROPERTY);
    map.putValue("file_name", _AvzTCabinetFile.FILE_NAME_PROPERTY);
    map.putValue("update_date", _AvzTCabinetFile.UPDATE_DATE_PROPERTY);
    map.putValue("file_size", _AvzTCabinetFile.FILE_SIZE_PROPERTY);
    // filter用
    map.putValue("folder", AvzTCabinetFile.FOLDER_ID_COLUMN);
    return map;
  }

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

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

  public boolean isFileCreatable() {
    return isFileCreatable;
  }

  public boolean isFolderCreatable() {
    return isFolderCreatable;
  }

  public boolean isReadable() {
    return isReadable;
  }

  public boolean isWritable() {
    return isWritable;
  }

  public boolean isDeletable() {
    return isDeletable;
  }

  public boolean isRoot() {
    return selected_folderinfo.getFolderId() == ExtCabinetUtils.ROOT_FODLER_ID;
  }

}
