# -*- coding: utf-8 -*-
from PyQt4 import QtGui

class GPSModule:
	""" This GPS Module implements a search tab, that allows the user to
	search for organism/reference names in the candidate list. Clicking the
	search results directly jumps to the right position in the candidate 
	list. """
	def __init__(self, GPS):
		self.name = 'Search Tab'
		self.GPS = GPS
		
		self.searchText = QtGui.QLineEdit()
		self.searchText.setToolTip('Enter a reference name to search for.')
		self.searchText.returnPressed.connect(self.find_reference)
		self.searchBtn  = QtGui.QPushButton('Find Reference')
		self.searchBtn.clicked.connect(self.find_reference)
		self.searchRes  = QtGui.QListWidget()
		self.searchRes.setMinimumHeight(150)
		self.searchRes.itemClicked.connect(self.view_search_result)
		
		searchGrid = QtGui.QGridLayout()
		searchGrid.addWidget(self.searchText,0,0)
		searchGrid.addWidget(self.searchBtn, 0,1)
		searchGrid.addWidget(self.searchRes, 1,0,1,2)
		
		searchWidget = QtGui.QWidget()
		searchWidget.setLayout(searchGrid)
		
		GPS.toolsTab.addTab(searchWidget,"Search")

	def find_reference(self):
		s_text = str(self.searchText.text()).lower()
		search_results = []
		for ref in self.GPS.references:
			if s_text in str(ref).lower():
				search_results.append(str(ref))
		self.searchRes.clear()
		if len(search_results) > 0:
			for ref in sorted(search_results):
				self.searchRes.addItem(QtGui.QListWidgetItem(ref))
		else:
			self.searchRes.addItem(QtGui.QListWidgetItem('No matching references found.'))
	
	def view_search_result(self, item):
		# View the item selected in the search results in the main window
		ref_name = str(item.text())
		group_id = self.GPS.ref2group[ref_name]
		group = self.GPS.treeView.invisibleRootItem().child(group_id)
		for i in range(group.childCount()):
			if str(group.child(i).text(0)) == ref_name:
				sel = group.child(i)
				break
		self.GPS.treeView.setCurrentItem(sel)
		self.GPS.treeView.expand(self.GPS.treeView.currentIndex())
		self.GPS.treeView.scrollToItem(self.GPS.treeView.currentItem())
		self.GPS.tree_item_clicked_handler(self.GPS.treeView.currentItem(),0)