package jp.ac.osaka_u.sparql;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import jp.ac.osaka_u.sanken.sparql.FindCondition;

/**
 * 検索ヒストリを管理する
 * @author kato
 *
 */
public class History implements Serializable {

	/**
	 *
	 */
	private static final long serialVersionUID = -3553651124296192740L;
	private int historyIndex = 0;
	private List<List<FindCondition>> history;  //  @jve:decl-index=0:

	public History(){
		history = new ArrayList<List<FindCondition>>();
	}

	public void initHistory(){
		this.history = new ArrayList<List<FindCondition>>();
		this.historyIndex = -1;
	}

	public void addHistory(List<FindCondition> conditions){
		if (this.historyIndex >= 0 && this.historyIndex < (this.history.size() - 1)){
			for (int i=this.history.size()-1; i > this.historyIndex; i--){
				this.history.remove(i);
			}
		}
		this.history.add(conditions);
		this.historyIndex++;
//		updateButtonStates();
	}

	public List<FindCondition> getPrev(){
		if (hasPrev()){
			--historyIndex;
//			updateButtonStates();
			return this.history.get(historyIndex);
		}
		return null;
	}

	public List<FindCondition> getNext(){
		if (hasNext()){
			++historyIndex;
//			updateButtonStates();
			return this.history.get(historyIndex);
		}
		return null;
	}

	public boolean hasPrev(){
		if (history.size() != 0 && historyIndex > 0){
			return true;
		}
		return false;
	}

	public boolean hasNext(){
		if ((historyIndex + 1) < history.size()){
			return true;
		}
		return false;
	}


	public int getHistoryIndex() {
		return historyIndex;
	}


	public void setHistoryIndex(int historyIndex) {
		this.historyIndex = historyIndex;
	}
}

class HistoryManager {
	public static History getHistoryData(String type, HttpServletRequest request){
		HttpSession session = request.getSession(true);
		History history = (History)session.getAttribute(type+"_history");

		if (history == null){
			return new History();
		}

		return history;

	}

	public static void updateHistoryData(History history, String type, HttpServletRequest request){
		HttpSession session = request.getSession(true);
		session.setAttribute(type+"_history", history);
	}
}
