/*******************************************************************************
* Copyright (c)                                                                *
*           2005   Tristan Allwood,                                            *
*           2005   Daniel Burke,                                               *
*           2005   Marc Hull,                                                  *
*           2005   Ekaterina Itskova,                                          *
*           2005   Steve Zymler                                                *
*                                                                              *
* Permission is hereby granted, free of charge, to any person obtaining a      *
* copy of this software and associated documentation files (the                *
* "Software"), to deal in the Software without restriction, including          *
* without limitation the rights to use, copy, modify, merge, publish,          *
* distribute, sublicense, and/or sell copies of the Software, and to           *
* permit persons to whom the Software is furnished to do so, subject to        *
* the following conditions:                                                    *
*                                                                              *
* The above copyright notice and this permission notice shall be included      *
* in all copies or substantial portions of the Software.                       *
*                                                                              *
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS      *
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF                   *
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.       *
* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY         *
* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,         *
* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE            *
* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.                       *
*******************************************************************************/
 /*
 * Created on 09-Nov-2004
 *
 */

package uk.ac.ic.doc.kevlar.gui.internal.taskpane.searchpane;

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

import org.eclipse.swt.graphics.GC;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.widgets.Display;

import uk.ac.ic.doc.kevlar.gui.GUIManager;
import uk.ac.ic.doc.kevlar.gui.internal.ADrawableObject;
import uk.ac.ic.doc.kevlar.gui.internal.caches.ImageCache;
import uk.ac.ic.doc.kevlar.gui.internal.keyboard.KeyboardManager;
import uk.ac.ic.doc.kevlar.gui.internal.keyboard.states.SearchPaneState;
import uk.ac.ic.doc.kevlar.gui.internal.taskpane.ATaskPane;
import uk.ac.ic.doc.kevlar.gui.internal.widgets.ISelectListener;
import uk.ac.ic.doc.kevlar.gui.internal.widgets.textbox.MultilineTextBox;
import uk.ac.ic.doc.kevlar.hial.IHial;
import uk.ac.ic.doc.kevlar.hial.IProgramSearchResult;

/**
 * @author Kate
 *
 */

public class SearchPane extends ATaskPane implements ISelectListener {
	
    private MultilineTextBox search;
	private Heading searchLabel;
	private SearchButton searchButton;
	private ResetButton resetButton;
	private ResultBox result;
	private Image background;
	
	public static final String SEARCH_BACKGROUND_IMAGE = "searchbk.png";
	public static final Point HEADING_POSITION = new Point(10,0);
	public static final Point SEARCH_BOX_POSITION = new Point(5,35);
	public static final Point SEARCH_BOX_SIZE = new Point(170, 50);	
	public static final int searchButtonY = SEARCH_BOX_POSITION.y+SearchBox.SEARCH_BOX_SIZE.y+2;
	public static final Point SEARCH_RESULT_HEADING_POSITION = new Point(0,searchButtonY+28);
	
	public SearchPane(Point position) {
	    
		initializePane();
			
	}
	
	private void initializePane() {
	    
		String message = "Type in the keywords you would like to search for:";
        searchLabel = new Heading(message, new Point(160, 30), HEADING_POSITION);
		addChild(searchLabel); 
        
        search = new MultilineTextBox();
        search.setPosition(SEARCH_BOX_POSITION);
        search.setSize(SEARCH_BOX_SIZE);
        search.setSelectListener(this);
		addChild(search);
        
		result = new ResultBox(this);
		result.setPosition(SEARCH_RESULT_HEADING_POSITION);
		result.setSizeFillBoth(new Point(0, 0));
		addChild(result);
		
		searchButton = new SearchButton(this);
		searchButton.setPosition(new Point(79, searchButtonY));
		searchButton.setAlignment(true, false);
		addChild(searchButton);
		
		resetButton = new ResetButton(this);
		resetButton.setPosition(new Point(5, searchButtonY));
		addChild(resetButton);
		
		try {
		
		    background = ImageCache.get(SEARCH_BACKGROUND_IMAGE);
		    
		} catch (FileNotFoundException e) {
		    
		    System.err.println("File not found: "+SEARCH_BACKGROUND_IMAGE);
		    background = new Image(Display.getDefault(), 1, 1);
		    
		}
		
	}
	
	public String getName() {
		
		return "Search";
	}
	
	public ResultBox getResultBox() {
	    
	    return result;
	    
	}
	
	public void search() {
	    
		List<String> keywords = new ArrayList<String>();
		String text = getTextBox().getText();
		
		keywords = getKeywords(text);
		
		search(keywords);
	    
	}
			
	public void search(List<String> keywords)
	{ 
	    
	    /* get search results from the hial, display results */
	    
	    IHial hial = GUIManager.getHial();
	    List<IProgramSearchResult> results = hial.search(keywords);
	    
	    result.displayResults(results); 
	    
	} 
	
	private List<String> getKeywords(String search)
	{
	    List<String> keywords = new ArrayList<String>();
	    int startPos = 0;
	    char previous = '$';
	    
	    for (int i = 0; i<search.length(); i++)
	    {
	        char current = search.charAt(i);
	        if (current==';' || current==' ' || current==',' || current=='\n')
	        {
	            if (previous==';' || previous==' ' || previous==',' || previous=='\n')
	            {
	                previous = search.charAt(i);
	                startPos = i+1;
	            }
	            else
	            {
	                String keyword = search.substring(startPos, i);
	                keywords.add(keyword.toLowerCase());
	                
	                startPos = i+1;
	                previous = search.charAt(i);
	            }
	        }
	        else
	        {
	            previous = current;
	        }
	        
	    }
	    
	    keywords.add(search.substring(startPos, search.length()));
	    
	    return keywords;
	}
	
	 public MultilineTextBox getTextBox() {
	     
	     return search;
	 	
	 }
	 
	 public void drawBefore(GC gc, Rectangle redrawArea) {
	     
	     gc.drawImage(background, -redrawArea.x, -redrawArea.y);
	     
	 }
	 
	 public void activate() {

	     if (!(KeyboardManager.getSingleton().getState() instanceof SearchPaneState)) {
	     
	         KeyboardManager.getSingleton().setState(new SearchPaneState());
	         
	     }
	     
	 }
	 
    public void onSelect(ADrawableObject object) {

	     if (!(KeyboardManager.getSingleton().getState() instanceof SearchPaneState)) {
		     
	         KeyboardManager.getSingleton().setState(new SearchPaneState());
		         
	     }        
        
    }
	 
}
