#!/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 QSettings, Qt, SIGNAL
from PyQt4.Qt import QVariant, QAbstractTableModel, QTableView

from PyQt4.QtGui import QProgressDialog, QMessageBox, QFileDialog

class DictionariesView(QTableView):
    def __init__(self, parent):
        QTableView.__init__(self, parent)

class DictionariesModel(QAbstractTableModel):
    def __init__(self, parent):
        QAbstractTableModel.__init__(self, parent)
        self._headers = [_("Type"), _("Dictionary name"), _("Total articles")]
        self._main = parent
        self.window = None
        self.rowSelected = None
        self.engine = parent.engine
        #check the list of dicts from registry
        self.dicts = self.engine.getDictionaries()

    def flags(self, index):
        flags = QAbstractTableModel.flags(self, index)
        if index.isValid():
            if index.row() == 0:
                flags |= Qt.ItemIsDropEnabled
        return flags

    def getMainApp(self):
        return self._main

    def getTotalRows(self):
        return len(self.engine.getDictionaries())

    def rowCount(self, index):
        return len(self.engine.getDictionaries())

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

    def headerData(self, section, orientation, role):
        if role != Qt.DisplayRole:
            return QVariant()
        text = ""
        if orientation == Qt.Horizontal:
            text = unicode(self._headers[section])
            return QVariant(text)
        else:
            return QVariant()

    def data(self, index, role):
        row, col = index.row(), index.column()
        if role == Qt.DisplayRole:
            if self.dicts[row] != None:
                if col == 0:
                    text = self.dicts[row].getTypeStr()
                elif col == 1:
                    text = self.dicts[row].getName()
                elif col == 2:
                    text = len(self.dicts[row])
            else:
                text = "Unknown"
            return QVariant(text)

        return QVariant()

    def onButtonRefreshDict(self):
        self.window = self.getMainApp().settingsDialog
        self.window.status_progress = QProgressDialog(_("Rescanning dictionaries..."), _("&Abort"), 0, 0, self.window)
        self.window.status_progress.setWindowTitle(_("Info"))
        self.window.setCursor(Qt.BusyCursor)
        self.window.status_progress.show()
        self.window.progress(-1)

        self.getMainApp().dictFileManager.loadDirectory()
        self.dicts = self.engine.getDictionaries()

        self.window.status_progress.close()
        self.window.setCursor(Qt.ArrowCursor)

    def onButtonInfoDict(self):
        if self.rowSelected != None:
            QMessageBox.about(self.getMainApp().window, _("Error"), self.dicts[self.rowSelected].getName())

    def onButtonMoveDownDict(self):
        pass

    def onButtonMoveUpDict(self):
        pass

    def onButtonDeleteDict(self):
        if self.rowSelected != None:
            self.emit(SIGNAL("layoutAboutToBeChanged()"))
            dictId = self.dicts[self.rowSelected].getUniqueId()
            dict = self.engine.getDictionary(dictId)
            self.getMainApp().dictFileManager.removeDictionaryFile(dict)
            self.engine.deleteDictionary(dictId)
            menuItem = self.getMainApp().menuCheckDictionaries[dictId]
            self.getMainApp().menuDictionaries.removeAction(menuItem)
            del self.getMainApp().menuCheckDictionaries[dictId]
            self.dicts = self.engine.getDictionaries()
            self.emit(SIGNAL("layoutChanged()"))
            if self.getMainApp().activeDictionary == dictId:
                self.getMainApp().onActivateDictionary(dictId, False)
                self.getMainApp().definitionView.setIntroduction()
                self.getMainApp().activeDictionary  = None
                self.getMainApp().onArticlesClearButton()
            self.getMainApp().settingsDialog.dictSelectionModel.clear()
            self.getMainApp().settingsDialog.updateButtonsDictionaries()

            self.getMainApp().updateActiveDictionary()

    def onButtonImportDict(self):
        self.getMainApp().onMenuImportDictionary()

        self.emit(SIGNAL("layoutAboutToBeChanged()"))
        self.dicts = self.engine.getDictionaries()
        self.emit(SIGNAL("layoutChanged()"))

    def onButtonExportDict(self):
        exportWildCard =  "Slowo dictionaries (*.dwa);;" \
               "Mova dictionaries (*.mova);;" \
               "DICT dictionaries (*.dz)"
        settings = QSettings()
        currentDir = settings.value("mainwindow/workingDirectory", QVariant())
        fileName = QFileDialog.getSaveFileName(None, _("Export dictionary as..."), currentDir.toString(), exportWildCard)
        type = None #TODO: Get the type of the dictionary choosen
        if fileName:
            QMessageBox.about(self.window, _("Error"), "Function not implemented yet.")
            #self.engine.exportDictionary(fileName, type)

