/* $Id: ResultListPanel.java 379 2011-10-03 14:30:29Z shayashi $ */
package smart_gs.text_search.swingui;

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

import smart_gs.logical.GSResource;
import smart_gs.logical.IDAT;
import smart_gs.logical.Spread;
import smart_gs.logical.URIObject;
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 count = 0;
	String query;
	ArrayList<SearchResult> results;
	
	public ResultListPanel(String query, int sizeToDisplay, int sizeOfResults,ArrayList<SearchResult> results){
		super(new GridLayout(sizeToDisplay, 1));
		count = 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 = count*sizeToDisplay; // 最初に表示する result の index
		int end = Math.min((count+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(count<=0){
			count =0;
			showResults();
		}else {
			count--;
			showResults();
		}
	}
	
	public void next(){
		if((count+1)*sizeToDisplay>=sizeOfResults){
			showResults();
		}else{
			count++;
			showResults();
		}
	}
}
