/* $Id: ResultListPanel.java 709 2013-07-08 02:56:53Z ohura $ */
package smart_gs.text_search.swingui;

import javax.swing.JPanel;
import javax.swing.border.TitledBorder;

import smart_gs.logical.IDAT;
import smart_gs.logical.Spread;
import smart_gs.logical.URISolver;
import smart_gs.swingui.WorkspaceWindow;
import smart_gs.text_search.logical.*;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.util.ArrayList;
import java.lang.Math;

@SuppressWarnings("serial")
public class ResultListPanel extends JPanel {
	private int sizeOfResults;
	private int sizeToDisplay;
	private int page = 0;
	String query;
	ArrayList<SearchResult> results;
	
	public ResultListPanel(String query, int sizeToDisplay, int sizeOfResults,ArrayList<SearchResult> results){
		super(new GridLayout(sizeToDisplay, 1));
		page = 0;
		this.sizeOfResults = sizeOfResults;
		this.sizeToDisplay = sizeToDisplay;
		this.setPreferredSize(new Dimension(250, 700));
		this.results = results;
		this.query = query;
		showResults();
	}
	
	private void showResults(){
		removeAll();
		int begin = page*sizeToDisplay; // 最初に表示する result の index
		int end = Math.min((page+1)*sizeToDisplay-1, sizeOfResults-1); // 最後に表示するresult の index
		
		WorkspaceWindow win = WorkspaceWindow.getInstance();
		boolean currentSpreadIsUndefined = (win.getSpread() == null);
		
		for(int i=begin; i<=end ; i++){
			SearchResult result = results.get(i);
			if (currentSpreadIsUndefined && result.isInAnIDAT()) {
				IDAT idat = (IDAT)(URISolver.getResource(result.getDocumentURL()));
				Spread spread = idat.getSpread();
				if (spread != null) {
					win.setSpread(spread);
					win.repaint();
				}
				currentSpreadIsUndefined = false;
			}
			ResultPanel panel = ResultPanel.getInstance(result.getTextToShow(), result.getDocumentURL(),result.getIndex());
			this.add(panel);
			panel.setPreferredSize(new Dimension(380, 40));
		}
		this.setBorder(new TitledBorder("Results " + (begin+1) + " - " +(end+1)+" of " +sizeOfResults+ " for \"" +query+ "\"" ));
	}
	
	public void back(){
		if(page<=0){
			page =0;
			showResults();
		}else {
			page--;
			showResults();
		}
	}
	
	public void next(){
		if((page+1)*sizeToDisplay>=sizeOfResults){
			showResults();
		}else{
			page++;
			showResults();
		}
	}

	public boolean isBackButton() {
		if(page<=0){
			return false;
		}
		return true;
	}
	
	public boolean isNextButton() {
		if((page+1)*sizeToDisplay>=sizeOfResults){
			return false;
		}
		return true;
	}
}
