#!/usr/bin/env python
# -*- coding: utf-8 -*-

#    Copyright (C) 2008-2010 Ivan Garcia <contact@ivangarcia.org>
#    This program is free software; you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation; either version 3 of the License, or
#    (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License along
#    with this program; if not, write to the Free Software Foundation, Inc.,
#    51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.

from PyQt4.QtCore import Qt, SIGNAL, QString
from PyQt4.Qt import QAbstractTableModel,  QVariant,  QModelIndex
from PyQt4.QtGui import QItemSelection

import traceback
import time

class ContentSearchModel(QAbstractTableModel):
    def __init__(self, parent):
        QAbstractTableModel.__init__(self, parent)
        self._headers = ["Words"]
        self._main = parent
        self.rowSelected = None
        self.engine = parent.engine
        #check the list of dicts from registry
        self.wordlist = []
        self.definitions = {}
        self.searched_word = ''
        self.status  = "stopped"

        self.connect(self, SIGNAL("percentageChanged(int)"), self.setPercentage)

    def flags(self, index):
        flags = QAbstractTableModel.flags(self, index)
        return flags

    def getMainApp(self):
        return self._main

    def rowCount(self, parent=QModelIndex()):
        return len(self.wordlist)

    def columnCount(self, parent):
        return len(self._headers)

    def getWordFromIndex(self, index):
        row = index.row()
        if self.wordlist[row] != None:
                return self.wordlist[row]
        else:
                raise IndexError

    def headerData(self, section, orientation, role):
        return QVariant()

    def data(self, index, role):
        if index.isValid() and role == Qt.DisplayRole:
            row, col = index.row(), index.column()
            if self.wordlist[row] != None:
                    text = self.wordlist[row]
            else:
                    text = "Unknown"
            return QVariant(text)

        return QVariant()

    def clear(self):
        self.emit(SIGNAL("layoutAboutToBeChanged()"))
        self.wordlist = []
        self.definitions = {}
        self.searched_word = ''
        self.emit(SIGNAL("layoutChanged()"))

    def addWord(self, word, content):
        self.emit(SIGNAL("layoutAboutToBeChanged()"))
        self.wordlist.append(word)
        self.definitions[word] = content
        self.emit(SIGNAL("layoutChanged()"))

    def setWordList(self, words):
        self.emit(SIGNAL("layoutAboutToBeChanged()"))
        self.wordlist = words
        self.emit(SIGNAL("layoutChanged()"))

    def getWordList(self):
        return self.wordlist

    def search(self, text):
        dict = self.engine.getDictionary(self.getMainApp().activeDictionary)
        #TODO: clone the dictionary to not have thread bug when accessing the content at the same time
        #dict = dict.copy()
        while self.status == "stopping" or self.status == "running":
            time.sleep(1)

        self.status = 'running'
        self.searched_word = text
        words = dict.getWords()
        percentage = 0
        for count, word in enumerate(words):
            try:
                    word, definition = dict[word]
                    content = definition.content()
                    if text in content :
                            self.addWord(word, content)
            except:
                print word
                traceback.print_exc()

            if  self.status == "stopping":
                self.status = "stopped"
                return

            if int(count/ 100) > percentage:
                    percentage += 1
                    self.emit(SIGNAL("percentageChanged(int)"), percentage)

        self.status  = "stopped"
        self.emit(SIGNAL("percentageChanged(int)"), 100)
        self.getMainApp().stopContentSearchButton.setEnabled(False)

    def setPercentage(self, number):
        if self.getMainApp().contentSearchProgress.value() < number:
                self.getMainApp().contentSearchProgress.setValue(number)

    def stopSearch(self):
        if self.status == "running":
            self.status = "stopping"
        self.emit(SIGNAL("percentageChanged(int)"), 0)

    def onClick(self, index):
        word = self.getWordFromIndex(index)
        content = self.definitions[word]
        highlighted_content  = self.highlight(self.searched_word, content)
        self.getMainApp().definitionView.setDefinition(word, highlighted_content)
        self.getMainApp().addWordToHistory(word, content)

    def highlight(self, word, content):
        highlighted = content.replace(word, '<FONT style="BACKGROUND-COLOR: yellow" COLOR="black"><b>%s</b></FONT>' % word)
        return highlighted

    def updateSelection(self):
        selected = self.getMainApp().historyListSelectionModel.selection()
        if selected.count():
            self.rowSelected = selected.last().bottomRight().row()
        else:
            self.rowSelected = None
