# -*- coding: utf-8 -*-

# -----------------------------------------------------------------
# This file is a part of PAMPI project.
# Name:         PAMPI
# Copyright:    (C) 2017-2021 Pascal PETER
# Licence:      GNU General Public Licence version 3
# Website:      http://pascal.peter.free.fr/
# Email:        pascal.peter at free.fr
# -----------------------------------------------------------------
# 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, see <http://www.gnu.org/licenses/>.
# -----------------------------------------------------------------

"""
DESCRIPTION :
    Ce module contient des fonctions utiles au programme.
"""


# importation des modules utiles :
from __future__ import division, print_function
import sys
import os

# importation des modules perso :
import utils

# PyQt5 ou PyQt4 :
if utils.PYQT == 'PYQT5':
    from PyQt5 import QtCore, QtWidgets, QtGui
else:
    from PyQt4 import QtCore, QtGui as QtWidgets, QtGui


"""
****************************************************
    POUR L'AFFICHAGE DES TEXTES
****************************************************
"""

def myPrint(*args):
    if len(args) > 1:
        print(args)
    else:
        arg = args[0]
        try:
            print(arg)
        except:
            try:
                print(u(arg))
            except:
                try:
                    print(s(arg))
                except:
                    print('PB in myPrint')

def u(text):
    # retourne une version unicode de text
    if utils.PYTHONVERSION >= 30:
        try:
            if isinstance(text, str):
                return text
            else:
                return str(text)
        except:
            myPrint('ERROR utils.u', type(text), text)
            return text
    else:
        try:
            return unicode(text)
        except:
            if isinstance(text, str):
                return text.decode('utf-8')
            elif isinstance(text, QtCore.QByteArray):
                return str(text).decode('utf-8')
            else:
                myPrint('ERROR utils.u', type(text), text)
                return text

def s(text):
    # retourne une version str de text
    if utils.PYTHONVERSION >= 30:
        if isinstance(text, str):
            return text
        else:
            try:
                return str(text)
            except:
                myPrint('ERROR utils.s', type(text), text)
                return text
    else:
        try:
            return text.encode('utf8')
        except:
            if isinstance(text, str):
                return text
            else:
                try:
                    return str(text)
                except:
                    myPrint('ERROR utils.s', type(text), text)
                    return text



"""
****************************************************
    MESSAGES, BOUTONS, ...
****************************************************
"""

def doWaitCursor():
    QtWidgets.QApplication.setOverrideCursor(QtCore.Qt.WaitCursor)

def restoreCursor():
    QtWidgets.QApplication.restoreOverrideCursor()

def messageBox(main, level='information', title='', message='',
               detailedText='',
               buttons=['Ok'], defaultButton=QtWidgets.QMessageBox.NoButton):
    """
    """
    # on teste l'aspect du curseur (doit être normal) :
    try:
        waitCursor = (QtWidgets.QApplication.overrideCursor().shape() == QtCore.Qt.WaitCursor)
    except:
        waitCursor = False
    if waitCursor:
        QtWidgets.QApplication.restoreOverrideCursor()
    # gestion des boutons (standards ou persos) :
    buttonsDic = {
        'Ok': QtWidgets.QMessageBox.Ok,
        'Yes': QtWidgets.QMessageBox.Yes,
        'No': QtWidgets.QMessageBox.No,
        'NoToAll': QtWidgets.QMessageBox.NoToAll,
        'Cancel': QtWidgets.QMessageBox.Cancel,
        'Open': QtWidgets.QMessageBox.Open,
        'Save': QtWidgets.QMessageBox.Save,
        'Discard': QtWidgets.QMessageBox.Discard,
        'Abort': QtWidgets.QMessageBox.Abort,
        'Close': QtWidgets.QMessageBox.Close,
        'Help': QtWidgets.QMessageBox.Help,
        }
    buttonsToAdd = []
    standardButtons = QtWidgets.QMessageBox.NoButton
    for button in buttons:
        if button in buttonsDic:
            standardButtons = standardButtons | buttonsDic[button]
        else:
            # les boutons persos seront ajoutés plus tard :
            buttonsToAdd.append(button)
    # titre de la fenêtre :
    titlesDic = {
        'information': QtWidgets.QApplication.translate('main', 'information message'),
        'question': QtWidgets.QApplication.translate('main', 'question message'),
        'warning': QtWidgets.QApplication.translate('main', 'warning message'),
        'critical': QtWidgets.QApplication.translate('main', 'critical message'),
        }
    if title == '':
        title = u('{0} ({1})').format(utils.PROGTITLE, titlesDic[level])
    # icône :
    iconsDic = {
        'information': QtWidgets.QMessageBox.Information,
        'question': QtWidgets.QMessageBox.Question,
        'warning': QtWidgets.QMessageBox.Warning,
        'critical': QtWidgets.QMessageBox.Critical,
        }
    icon = iconsDic[level]
    # on peut créer la boîte de dialogue :
    messageBox = QtWidgets.QMessageBox(icon, title, message, standardButtons, main)
    # on ajoute les boutons persos :
    for button in buttonsToAdd:
        if isinstance(button, tuple):
            theButton = QtWidgets.QPushButton(QtGui.QIcon(button[0]), button[1])
            messageBox.addButton(theButton, QtWidgets.QMessageBox.NoRole)
        else:
            messageBox.addButton(button, QtWidgets.QMessageBox.NoRole)
    # le texte détaillé s'il existe :
    if detailedText != '':
        messageBox.setDetailedText(detailedText)
    # on affiche la boîte :
    result = messageBox.exec_()
    # on remet le curseur wait si besoin :
    if waitCursor:
        QtWidgets.QApplication.setOverrideCursor(QtCore.Qt.WaitCursor)
    return result

def afficheStatusBar(main, message=''):
    # pour afficher message dans la StatusBar de la fenêtre principale
    try:
        main.statusBar().showMessage(u(message))
    except:
        pass

def afficheMsgFinOpenDir(main, directory, message=''):
    restoreCursor()
    endMessage = QtWidgets.QApplication.translate('main', 'END !')
    openMessage = QtWidgets.QApplication.translate(
        'main', 'Images are saved in the folder:')
    if message != '':
        message = u('<p>{0}</p>').format(message)
    allMessage = u(
        '<p align="center">__________________________</p>'
        '<p align="center"><b>{0}</b></p>'
        '<p>{1}</p>'
        '{2}<p></p>').format(endMessage, openMessage, message)
    reply = QtWidgets.QMessageBox.information(
        main, utils.PROGTITLE, allMessage,
        QtWidgets.QMessageBox.Ok | QtWidgets.QMessageBox.Open)
    if reply == QtWidgets.QMessageBox.Open:
        import utils_filesdirs
        utils_filesdirs.openDir(directory)



"""
****************************************************
    DIVERS
****************************************************
"""

def doLocale(locale, beginFileName, endFileName, defaultFileName=''):
    """
    Teste l'existence d'un fichier localisé.
    Par exemple, insère _fr_FR ou _fr entre beginFileName et endFileName.
    Renvoie le fichier par défaut sinon.
    """
    # on teste d'abord avec locale (par exemple fr_FR) :
    localeFileName = u('{0}_{1}{2}').format(beginFileName, locale, endFileName)
    if QtCore.QFileInfo(localeFileName).exists():
        return localeFileName
    # ensuite avec lang (par exemple fr) :
    lang = locale.split('_')[0]
    localeFileName = u('{0}_{1}{2}').format(beginFileName, lang, endFileName)
    if QtCore.QFileInfo(localeFileName).exists():
        return localeFileName
    # si defaultFileName est spécifié :
    if defaultFileName != '':
        return u(defaultFileName)
    # sinon on renvoie le fichier de départ :
    localeFileName = u('{0}{1}').format(beginFileName, endFileName)
    return localeFileName

def addSlash(aDir):
    """
    pour ajouter un / à la fin d'un nom de dossier si besoin
    aDir = utils_functions.addSlash(aDir)
    """
    if aDir[-1] != '/':
        aDir = aDir + '/'
    return aDir

def removeSlash(aDir):
    """
    pour supprimer l'éventuel / à la fin d'un nom de dossier
    aDir = utils_functions.removeSlash(aDir)
    """
    if len(aDir) > 0:
        if aDir[-1] == '/':
            aDir = aDir[:-1]
    return aDir

def longFileName(path, fileName):
    """
    Construit un "nom allongé" de fichier pour vérifier sa disponibilité
    dans le dossier des fichiers markdown
    @param path le chemin vers les présentations
    @param filename le nom de fichier à trouver
    @return un chemin complet
    """
    return u('{0}/md/{1}').format(path, fileName)
