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

import java.util.List;

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.eip.cayenne.om.portlet.AvzTSearchMap;
import com.aimluck.eip.common.ALEipConstants;
import com.aimluck.eip.common.ALPageNotFoundException;
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;

/**
 * SearchMapのユーティリティクラスです。 <BR>
 * 
 */
public class SearchMapUtils {

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

  // 検索キーワードの重複チェックを行います。
  public static boolean isDuplicate(RunData rundata, Context context) {
    try {
      SelectQuery<AvzTSearchMap> query = Database.query(AvzTSearchMap.class);
      Expression exp =
        ExpressionFactory.matchExp(AvzTSearchMap.USER_ID_PROPERTY, Integer
          .valueOf(ALEipUtils.getUserId(rundata)));
      exp =
        exp.andExp(ExpressionFactory.matchExp(
          AvzTSearchMap.KEYWORD_PROPERTY,
          rundata.getParameters().getString("keyword")));
      query.setQualifier(exp);
      ResultList<AvzTSearchMap> list = query.getResultList();
      if (list.size() != 0) {
        return true;
      }

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

  /**
   * SearchMap オブジェクトモデルを取得します。 <BR>
   * 
   * @param rundata
   * @param context
   * @return
   */
  public static AvzTSearchMap getAvzTSearchMap(RunData rundata, Context context)
      throws ALPageNotFoundException {
    String id = ALEipUtils.getTemp(rundata, context, ALEipConstants.ENTITY_ID);
    try {
      if (id == null || "".equals(id) || Integer.valueOf(id) == null) {
        id = rundata.getParameters().getString(ALEipConstants.ENTITY_ID);
        if (id == null || "".equals(id) || Integer.valueOf(id) == null) {
          // SearchMap IDが空の場合
          logger.debug("[SearchMapUtils] Empty ID...");
          return null;
        }
      }
      AvzTSearchMap searchmap =
        getAvzTSearchMap(rundata, context, Integer.valueOf(id));
      return searchmap;
    } catch (ALPageNotFoundException pageNotFound) {
      throw pageNotFound;
    } catch (Exception ex) {
      logger.error("Exception", ex);
      return null;
    }
  }

  /**
   * SearchMap オブジェクトモデルを取得します。 <BR>
   * 
   * @param rundata
   * @param context
   * @return
   */
  public static AvzTSearchMap getAvzTSearchMap(RunData rundata,
      Context context, Integer id) throws ALPageNotFoundException {
    int uid = ALEipUtils.getUserId(rundata);
    try {
      if (id == null) {
        // SearchMap IDが空の場合
        logger.debug("[SearchMapUtils] Empty ID...");
        return null;
      }
      SelectQuery<AvzTSearchMap> query = Database.query(AvzTSearchMap.class);
      Expression exp =
        ExpressionFactory.matchDbExp(AvzTSearchMap.ID_PK_COLUMN, id);
      exp.andExp(ExpressionFactory.matchExp(
        AvzTSearchMap.USER_ID_PROPERTY,
        Integer.valueOf(ALEipUtils.getUserId(rundata))));
      query.setQualifier(exp);
      List<AvzTSearchMap> searchmaps = query.getResultList();
      if (searchmaps == null || searchmaps.size() == 0) {
        // 指定したSearchMap IDのレコードが見つからない場合
        logger.debug("[SearchMapUtils] Not found ID...");
        return null;
      }

      // アクセス権の判定
      AvzTSearchMap searchmap = searchmaps.get(0);
      if (uid != searchmap.getUserId().intValue()) {
        logger.debug("[SearchMapUtils] Invalid user access...");
        throw new ALPageNotFoundException();
      }

      return (searchmaps.get(0));
    } catch (ALPageNotFoundException pageNotFound) {
      logger.error(pageNotFound);
      throw pageNotFound;
    } catch (Exception ex) {
      logger.error("Exception", ex);
      return null;
    }
  }

  public String sanitizing(String string) {
    string = string.replaceAll("&", "&amp;");
    string = string.replaceAll("<", "&lt;");
    string = string.replaceAll(">", "&gt;");
    string = string.replaceAll("\"", "&quot;");
    string = string.replaceAll("'", "&#39;");
    return string;

  }
}
