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

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
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.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.query.ResultList;
import com.aimluck.eip.rss.util.RssUtils;
import com.aimluck.eip.util.ALEipUtils;

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

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

  /** RSS配信URLの一覧 */
  private List<UrlResultData> urlList;

  /**
   * RSS配信URLの一覧取得 PSMLファイルより取得します。
   */
  public void loadUrlList(VelocityPortlet portlet, RunData rundata) {
    urlList = RssUtils.getTitles(portlet, rundata);
  }

  /**
   * RSS配信URLの一覧取得 velocityからのアクセスに使用します。
   */
  public List<UrlResultData> getUrlList() {
    return urlList;
  }

  @Override
  public void init(ALAction action, RunData rundata, Context context)
      throws ALPageNotFoundException, ALDBErrorException {

    super.init(action, rundata, context);

    // グループの初期値を取得する
    try {
      String filter = ALEipUtils.getTemp(rundata, context, LIST_FILTER_STR);
      if (filter == null || filter.equals("")) {
        VelocityPortlet portlet = ALEipUtils.getPortlet(rundata, context);
        String groupName =
          portlet.getPortletConfig().getInitParameter("pca-group");
        if (groupName != null) {
          ALEipUtils.setTemp(rundata, context, LIST_FILTER_STR, groupName);
          ALEipUtils.setTemp(rundata, context, LIST_FILTER_TYPE_STR, "group");
        }
      }
    } catch (Exception ex) {
      logger.debug("Exception", ex);
    }
  }

  /**
   * 一覧データを取得します。 <BR>
   * 
   * @param rundata
   * @param context
   * @return
   * @throws IOException
   * @see com.aimluck.eip.common.ALAbstractListData#selectData(org.apache.turbine.util.RunData,
   *      org.apache.velocity.context.Context)
   */
  @Override
  public ResultList selectList(RunData rundata, Context context)
      throws ALDBErrorException {
    List<RssResultData> list = new ArrayList<RssResultData>();
    try {
      String filter = ALEipUtils.getTemp(rundata, context, LIST_FILTER_STR);
      String filter_type =
        ALEipUtils.getTemp(rundata, context, LIST_FILTER_TYPE_STR);

      for (UrlResultData url : urlList) {
        if (filter == null
          || ("").equals(filter)
          || ("all").equals(filter)
          || url.getNo().getValue().equals(filter)) {
          List<RssResultData> tmp =
            RssUtils.readRSS(url.getLink().toString(), getStrLength());
          list.addAll(tmp);
        }
      }

      // 日付順で降順ソート
      Collections.sort(list, new Comparator<RssResultData>() {
        public int compare(RssResultData t1, RssResultData t2) {
          if (t1.getPublishedDate() == null || t2.getPublishedDate() == null) {
            // RSS0.91では、公開日付がnullになることに対応
            return 0;
          }
          return -t1.getPublishedDate().compareTo(t2.getPublishedDate());
        }
      });

      // for( RssResultData d : resultList ) {
      // System.out.println(d.getFeedTitle() + " " + d.getTitle() + " " +
      // d.getPublishedDate());
      // }

      current_filter = filter;
      current_filter_type = filter_type;

      // return buildPaginatedList(resultList);

      List<RssResultData> paged_list = buildPaginatedList(list);
      ResultList<RssResultData> result = new ResultList<RssResultData>();
      for (RssResultData r : paged_list) {
        result.add(r);
      }

      return result;
    } catch (Exception e) {
      logger.error("Read RSS IOException", e);
      throw new ALDBErrorException();
    }
  }

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

  @Override
  public String getAclPortletFeature() {
    // TODO 自動生成されたメソッド・スタブ
    return null;
  }

  @Override
  protected Attributes getColumnMap() {
    // TODO 自動生成されたメソッド・スタブ
    return null;
  }

  @Override
  protected Object getResultDataDetail(Object obj)
      throws ALPageNotFoundException, ALDBErrorException {
    // TODO 自動生成されたメソッド・スタブ
    return null;
  }

  @Override
  protected Object selectDetail(RunData rundata, Context context)
      throws ALPageNotFoundException, ALDBErrorException {
    // TODO 自動生成されたメソッド・スタブ
    return null;
  }
}
