#!/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, QObject, QSettings, QVariant, QCoreApplication
from PyQt4.QtGui import QMessageBox, QFileDialog, QItemSelectionModel, QDialog

from settings_ui import Ui_SettingsDialog
import webbrowser
import time, thread, platform
import logging
import core.languages.availablelanguages as availablelanguages

from dictionariesview import DictionariesModel
from onlineDictionariesView import OnlineDictionariesModel

log = logging.getLogger("babiloo.gui.settings")

class settingsDialog(QDialog):
    def __init__(self, parent):
        QDialog.__init__(self)
        self.ui = Ui_SettingsDialog()
        self.ui.setupUi(self)
        self._main  = parent
        self.settings = self._main.settings

        self.initDictionaries()
        self.SetSignals()

        self.TAB_DICTIONARIES = 1
        self.TAB_MANAGE_DICTIONARIES = 0
        self.TAB_DOWNLOAD_DICTIONARIES = 1
        self.readSettings()

    def SetSignals(self):
        QObject.connect(self.ui.exportDictButton, SIGNAL("clicked(bool)"), self.dictionariesModel.onButtonExportDict)
        QObject.connect(self.ui.importDictButton, SIGNAL("clicked(bool)"), self.dictionariesModel.onButtonImportDict)
        QObject.connect(self.ui.deleteDictButton, SIGNAL("clicked(bool)"), self.dictionariesModel.onButtonDeleteDict)
        QObject.connect(self.ui.moveDownDictButton, SIGNAL("clicked(bool)"), self.dictionariesModel.onButtonMoveDownDict)
        QObject.connect(self.ui.moveUpDictButton, SIGNAL("clicked(bool)"), self.dictionariesModel.onButtonMoveUpDict)
        QObject.connect(self.ui.infoDictButton, SIGNAL("clicked(bool)"), self.dictionariesModel.onButtonInfoDict)
        QObject.connect(self.ui.refreshDictButton, SIGNAL("clicked(bool)"), self.dictionariesModel.onButtonRefreshDict)
        QObject.connect(self.ui.dictionariesFolderButton, SIGNAL("clicked(bool)"), self.onChangeDefaultDictionaryDirectory)
        #Download dictionaries
        QObject.connect(self.ui.downloadFromLinkButton, SIGNAL("clicked(bool)"), self.onlineDictionariesModel.onButtonDownloadFromLink)
        #QObject.connect(self.ui.downloadLinkEdit, SIGNAL("clicked(bool)"), self.dictionariesModel.onDownloadLinkEdit)
        QObject.connect(self.ui.downloadFromListButton, SIGNAL("clicked(bool)"), self.onlineDictionariesModel.onButtonDownloadFromList)
        QObject.connect(self.ui.infoOnlineDictButton, SIGNAL("clicked(bool)"), self.onlineDictionariesModel.onButtonInfoOnlineDict)
        QObject.connect(self.ui.refreshOnlineDictButton, SIGNAL("clicked(bool)"), self.onlineDictionariesModel.onButtonRefreshOnlineDict)

        QObject.connect(self.dictSelectionModel, SIGNAL("selectionChanged(QItemSelection, QItemSelection)"), self.onDictionariesSelection)

        #QObject.connect(self.onlineDictionariesSelectionModel, SIGNAL("selectionChanged(QItemSelection, QItemSelection)"), self.onlineDictionariesModel.onDictionariesSelection)

        QObject.connect(self.ui.helpTranslateButton, SIGNAL("clicked(bool)"), self.onOptionHelpTranslateButton)
        QObject.connect(self.ui.buttonAccept, SIGNAL("clicked(bool)"), self.saveSettings)
        QObject.connect(self.ui.buttonCancel, SIGNAL("clicked(bool)"), self.cancelSettings)



        self.ui.downloadFromListButton.setEnabled(False)
        self.ui.infoOnlineDictButton.setEnabled(False)

    def changeTab(self, tabNumber):
        self.ui.tabWidget.setCurrentIndex(tabNumber)

    def onOptionInterfaceLanguage(self, option):
        QMessageBox.about(self,_("Alert"),_("The new language will be displayed after restarting the program."))

    def readSettings(self):
        languages = {}
        for lang_locale in self._main.interface_langs:
                languageName = availablelanguages.locale2name(lang_locale)
                if not languageName:
                    languageName = lang_locale
                languages[languageName] = lang_locale
        langs = languages.keys()
        langs.sort()
        for lang in langs:
            self.ui.optionInterfaceLanguage.addItem(lang, QVariant(languages[lang]))

        self.ui.optionInterfaceLanguage.adjustSize()
        optionInterfaceLanguage = self.settings.value("settings/interfaceLang", QVariant("en"))
        index = self.ui.optionInterfaceLanguage.findData(optionInterfaceLanguage)
        if index != -1 :
            self.ui.optionInterfaceLanguage.setCurrentIndex (index)

        QObject.connect(self.ui.optionInterfaceLanguage, SIGNAL("currentIndexChanged(int)"), self.onOptionInterfaceLanguage)

        optionAutoComplete = self.settings.value("settings/autoComplete", QVariant(True))
        self.ui.autoComplete.setChecked(optionAutoComplete.toBool())
        optionIgnoreAccents = self.settings.value("settings/ignoreAccents", QVariant(True))
        self.ui.ignoreAccents.setChecked(optionIgnoreAccents.toBool())
        optionCaseSensitive = self.settings.value("settings/caseSensitive", QVariant(False))
        self.ui.caseSensitive.setChecked(optionCaseSensitive.toBool())

        defaultDirectory = self.settings.value("settings/dictsDefaultDirectory", QVariant(True))

        self.ui.dictionariesFolderEdit.setText(defaultDirectory.toString())
        self.ui.autoComplete.setChecked(optionAutoComplete.toBool())

    def cancelSettings(self):
        self.reject()

    def saveSettings(self):
        log.debug("Saving Options Settings")

        optionInterfaceLanguage = self.ui.optionInterfaceLanguage.itemData(self.ui.optionInterfaceLanguage.currentIndex())
        self.settings.setValue("settings/interfaceLang", QVariant(optionInterfaceLanguage))

        optionAutoComplete = self.ui.autoComplete.isChecked()
        self.settings.setValue("settings/autoComplete", QVariant(optionAutoComplete))
        optionIgnoreAccents = self.ui.ignoreAccents.isChecked()
        self.settings.setValue("settings/ignoreAccents", QVariant(optionIgnoreAccents))
        optionCaseSensitive = self.ui.caseSensitive.isChecked()
        self.settings.setValue("settings/caseSensitive", QVariant(optionCaseSensitive))

        defaultDirectory = self.ui.dictionariesFolderEdit.text()
        self.settings.setValue("settings/dictsDefaultDirectory", QVariant(defaultDirectory))
        self.accept()

    def onChangeDefaultDictionaryDirectory(self):
        currentDir = self.settings.value("mainwindow/workingDirectory", QVariant())
        dir = QFileDialog.getExistingDirectory(None, _("Open Directory"),currentDir.toString(), QFileDialog.ShowDirsOnly)
        if dir:
            self.ui.dictionariesFolderEdit.setText(dir)

    def initDictionaries(self):
        engine = self._main.engine
        self.dictionariesModel = DictionariesModel(self._main)
        self.ui.dictsTable.setModel(self.dictionariesModel)
        self.dictSelectionModel = QItemSelectionModel(self.dictionariesModel)
        self.ui.dictsTable.setSelectionModel(self.dictSelectionModel)

        self.onlineDictionariesModel = OnlineDictionariesModel(self._main)
        #self.onlineDictionariesSelectionModel = QItemSelectionModel(self.onlineDictionariesModel)
        self.ui.onlineDictionariesView.setModel(self.onlineDictionariesModel)
        #self.ui.onlineDictionariesView.setSelectionModel(self.onlineDictionariesSelectionModel)

        QObject.connect(self.onlineDictionariesModel, SIGNAL("dataChanged(QModelIndex,QModelIndex)"), self.onSelectOnlineDictionariesView)
        QObject.connect(self.ui.onlineDictionariesView, SIGNAL("activated(QModelIndex)"), self.onClickOnlineDictionariesView)
        QObject.connect(self.ui.onlineDictionariesView, SIGNAL("clicked(QModelIndex)"), self.onClickOnlineDictionariesView)
        #QObject.connect(self.onlineDictionariesView, SIGNAL("customContextMenuRequested(QPoint)"), self.onContext)
        QObject.connect(self.onlineDictionariesModel, SIGNAL("updatedOnlineDictionaries()"), self.onUpdatedOnlineDictionaries)

        #self.onlineDictionariesModel.clearTree()

        thread.start_new_thread(self.onlineDictionariesModel.refreshOnlineDict, ())

        self.ui.dictsTable.resizeRowsToContents()
        self.ui.dictsTable.resizeColumnsToContents()
        self.updateButtonsDictionaries()

    def onClickOnlineDictionariesView(self, index):
        treeItem = self.onlineDictionariesModel.getSelectedItem(index)
        if treeItem.data["type"]  == "dict":
            treeItem.checked = not(treeItem.checked)
            self.ui.infoOnlineDictButton.setEnabled(True)
            self.onlineDictionariesModel.emit(SIGNAL("dataChanged(QModelIndex,QModelIndex)"),index, index)
            if len(self.onlineDictionariesModel.getCheckedDictionaries()):
                self.ui.downloadFromListButton.setEnabled(True)
            else:
                self.ui.downloadFromListButton.setEnabled(False)
        else:
            self.ui.infoOnlineDictButton.setEnabled(False)


    def onSelectOnlineDictionariesView(self):
        self.onlineDictionariesModel.getCheckedDictionaries()

    def updateButtonsDictionaries(self):
        self.ui.dictsTable.resizeRowsToContents()
        selected = self.dictSelectionModel.selection()
        if selected.count():
            self.dictionariesModel.rowSelected = selected.last().bottomRight().row()
            self.ui.exportDictButton.setEnabled(True)
            self.ui.deleteDictButton.setEnabled(True)
            self.ui.moveDownDictButton.setEnabled(False) #disabled temporarily
            self.ui.moveUpDictButton.setEnabled(False) #disabled temporarily
            self.ui.infoDictButton.setEnabled(True)
        else:
            self.dictionariesModel.rowSelected = None
            self.ui.exportDictButton.setEnabled(False)
            self.ui.deleteDictButton.setEnabled(False)
            self.ui.moveDownDictButton.setEnabled(False)
            self.ui.moveUpDictButton.setEnabled(False)
            self.ui.infoDictButton.setEnabled(False)

    def onDictionariesSelection(self, selected, unselected):
        self.updateButtonsDictionaries()

    def onUpdatedOnlineDictionaries(self):
        self.ui.onlineDictionariesView.expandAll()
#        locale_lang_index = self.onlineDictionariesModel.getIndexFromLanguage('vi')
#        if locale_lang_index:
#                self.ui.onlineDictionariesView.expand()

    def onOptionHelpTranslateButton(self):
        webbrowser.open( "http://www.babiloo-project.org/translate.html", new=2, autoraise=1)

    #Control the STATUS BAR PROGRESS
    def progress(self, val = None,msg = None):
        #by calling progres(), it will return False if it has been canceled
        if (val == None and msg == None ):
            return not self.status_progress.wasCanceled()

        if msg != None:
            self.status_progress.setLabelText(msg)
        if val < 0:
            self.status_progress.setMaximum(0)
        else:
            self.status_progress.setValue(val)
        QCoreApplication.processEvents()
        for i in range(1000):
            i = i * 5
            QCoreApplication.processEvents()
