# -*- 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 :
    blablabla
"""

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


"""
****************************************************
    VERSIONS DE PYTHON, QT, ETC
****************************************************
"""

# version de Python :
PYTHONVERSION = sys.version_info[0] * 10 + sys.version_info[1]

# PyQt5 ou PyQt4 :
PYQT = ''
if 'PYQT4' in sys.argv:
    try:
        import sip
        sip.setapi('QString', 2)
        sip.setapi('QVariant', 2)
        from PyQt4 import QtCore, QtGui as QtWidgets, QtGui
        PYQT = 'PYQT4'
    except:
        pass
else:
    try:
        # on teste d'abord PyQt5 :
        from PyQt5 import QtCore, QtWidgets, QtGui
        PYQT = 'PYQT5'
    except:
        # puis PyQt4 :
        try:
            import sip
            sip.setapi('QString', 2)
            sip.setapi('QVariant', 2)
            from PyQt4 import QtCore, QtGui as QtWidgets, QtGui
            PYQT = 'PYQT4'
        except:
            pass
if PYQT == '':
    print('YOU MUST INSTALL PYQT !')
else:
    print('PYTHONVERSION:', PYTHONVERSION, 'PYQT:', PYQT)

# version de Qt :
qtVersion = QtCore.qVersion()

# détection du système (nom et 32 ou 64) :
OS_NAME = ['', '']
def detectPlatform():
    global OS_NAME
    # 32 ou 64 bits :
    if sys.maxsize > 2**32:
        bits = 64
    else:
        bits = 32
    # platform et osName :
    platform = sys.platform
    osName = ''
    if platform.startswith('linux'):
        osName = 'linux'
    elif platform.startswith('win'):
        osName = 'win'
    elif platform.startswith('freebsd'):
        osName = 'freebsd'
    elif platform.startswith('darwin'):
        import platform
        if 'powerpc' in platform.uname():
            osName = 'powerpc'
        else:
            osName = 'mac'
    OS_NAME = [osName, bits]
detectPlatform()

MODEBAVARD = False
if 'MODEBAVARD' in sys.argv:
    MODEBAVARD = True



"""
****************************************************
    VARIABLES LIÉES AU LOGICIEL
****************************************************
"""

PROGTITLE = 'PAMPI'
PROGNAME = 'pampi'
PROGVERSION = '1.1___2021-02'
HELPPAGE = 'http://pascal.peter.free.fr/pampi.html'



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

DEFAULTCONFIG = {
    'LASTFILES': [], 
    'OTHER': {
        'presentationsDir': '', 
        },
    'TOOLS': {
        'ORDER': ['KaTeX', 'Vis', 'D3', 'JSXGraph', 'GeoGebra'], 
        'KaTeX': {
            'HEAD': [
                '<link rel="stylesheet" href="assets/tools/katex/katex.min.css">', 
                '<script src="assets/tools/katex/katex.min.js"></script>', 
                '<script src="assets/tools/katex/auto-render.min.js"></script>'], 
            'END': ['<script src="assets/tools/katex/my.js"></script>']
            }, 
        'Vis': {
            'HEAD': [
                '<link rel="stylesheet" href="assets/tools/Vis/vis.min.css">', 
                '<script src="assets/tools/Vis/vis.min.js"></script>'], 
            'END': []
            }, 
        'D3': {
            'HEAD': [
                '<link rel="stylesheet" href="assets/tools/D3/c3.css">', 
                '<script src="assets/tools/D3/d3.v3.min.js"></script>', 
                '<script src="assets/tools/D3/c3.min.js"></script>', 
                '<script src="assets/tools/D3/xkcd.js"></script>'], 
            'END': []
            }, 
        'JSXGraph': {
            'HEAD': [
                '<link rel="stylesheet" type="text/css" href="assets/tools/JSXGraph/jsxgraph.css">', 
                '<script src="assets/tools/JSXGraph/jsxgraphcore.js"></script>'], 
            'END': []
            }, 
        'GeoGebra': {
            'HEAD': ['<script src="assets/tools/GeoGebra/deployggb.js"></script>',], 
            'END': []
            }, 
        },
    }

DEFAULTCOLOR = '#ced8db'


STYLE = {}
def loadStyle():
    global STYLE
    style = QtWidgets.QApplication.style()
    STYLE = {
        'PM_ToolBarIconSize': style.pixelMetric(QtWidgets.QStyle.PM_ToolBarIconSize), 
        'PM_LargeIconSize': style.pixelMetric(QtWidgets.QStyle.PM_LargeIconSize), 
        #'PM_SmallIconSize': style.pixelMetric(QtWidgets.QStyle.PM_SmallIconSize), 
        #'PM_IconViewIconSize': style.pixelMetric(QtWidgets.QStyle.PM_IconViewIconSize), 
        #'PM_ListViewIconSize': style.pixelMetric(QtWidgets.QStyle.PM_ListViewIconSize), 
        #'PM_TabBarIconSize': style.pixelMetric(QtWidgets.QStyle.PM_TabBarIconSize), 
        #'PM_MessageBoxIconSize': style.pixelMetric(QtWidgets.QStyle.PM_MessageBoxIconSize), 
        #'PM_ButtonIconSize': style.pixelMetric(QtWidgets.QStyle.PM_ButtonIconSize), 
        }


SUPPORTED_IMAGE_FORMATS = ('png',)

def loadSupportedImageFormats():
    global SUPPORTED_IMAGE_FORMATS
    SUPPORTED_IMAGE_FORMATS = QtGui.QImageReader.supportedImageFormats()

def doIcon(fileName='', ext='svg', what='ICON'):
    if ext in SUPPORTED_IMAGE_FORMATS:
        allFileName = 'images/{0}.{1}'.format(fileName, ext)
    else:
        allFileName = 'images/png/{0}.png'.format(fileName)
    if not(QtCore.QFile(allFileName).exists()):
        print('doIcon:', allFileName)
        allFileName = 'images/png/{0}.png'.format(fileName)
    if what == 'ICON':
        return QtGui.QIcon(allFileName)
    else:
        return QtGui.QPixmap(allFileName)

DOCUMENTSLOCATION = None # emplacement des documents

def definePathsAndConfig(obj):
    """
    Trouve les chemins système et la configuration, puis les
    ajoute comme attributs de l'objet donné
    @param obj la fenêtre principale de l'application
    """
    global DOCUMENTSLOCATION
    import utils_filesdirs

    obj.beginDir = QtCore.QDir.currentPath()
    obj.configDir, first = utils_filesdirs.createConfigAppDir(PROGNAME)
    obj.tempPath = utils_filesdirs.createTempAppDir(PROGNAME + '-temp')
    obj.configDict = utils_filesdirs.readConfigFile(obj.configDir)
    obj.presentationsDir = obj.configDict['OTHER']['presentationsDir']
    
    # on détermine le dossier des documents
    if PYQT == 'PYQT5':
        location = QtCore.QStandardPaths.standardLocations(
            QtCore.QStandardPaths.DocumentsLocation)
    else:
        location = QtGui.QDesktopServices.storageLocation(
            QtGui.QDesktopServices.DocumentsLocation)
    if isinstance(location, list):
        location = location[0]
    DOCUMENTSLOCATION = location

    # on détermine le dossier pour les documents PDF
    if QtCore.QFileInfo(DOCUMENTSLOCATION).isDir():
        obj.pdfDir = DOCUMENTSLOCATION
    else:
        obj.pdfDir = QtCore.QDir.homePath()
        
    # on rectifie, quitte à le créer, le dossier des présentations.
    pDir = obj.presentationsDir
    if not(QtCore.QFileInfo(pDir).isDir()):
        if not(QtCore.QFileInfo(DOCUMENTSLOCATION).isDir()):
            # sélection du dossier de destination :
            DOCUMENTSLOCATION = QtWidgets.QFileDialog.getExistingDirectory(
                self, 
                QtWidgets.QApplication.translate(
                    'main', 'Select a directory for presentations'), 
                DOCUMENTSLOCATION, 
                QtWidgets.QFileDialog.DontResolveSymlinks | QtWidgets.QFileDialog.ShowDirsOnly)
            if isinstance(DOCUMENTSLOCATION, tuple):
                DOCUMENTSLOCATION = DOCUMENTSLOCATION[0]
        utils_functions.doWaitCursor()
        utils_filesdirs.createDirs(
            DOCUMENTSLOCATION, 'presentations')
        utils_filesdirs.copyDir(
            utils_functions.u('{0}/presentations').format(
                obj.beginDir), 
            utils_functions.u('{0}/presentations').format(
                DOCUMENTSLOCATION))
        #print('DOSSIER COPIE')
        utils_functions.restoreCursor()
        pDir = utils_functions.u(
            '{0}/presentations').format(DOCUMENTSLOCATION)
        #print('presentationsDir:', self.presentationsDir)
        obj.presentationsDir = pDir
    return

def updateLastFiles(obj):
    """
    Mise à jour de la liste des fichiers récents, pour l'application
    @param obj : le fenêtre principale
    """
    import utils_functions
    obj.configDict['LASTFILES'] = \
         [f for f in obj.configDict['LASTFILES'] \
          if QtCore.QFileInfo(utils_functions.longFileName(obj.presentationsDir, f)).isFile()]
    return

