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

# -----------------------------------------------------------------
# This file is a part of PAMPI project.
# Name:         PAMPI
# Copyright:    (C) 2017-2024 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 :
import os

import utils, utils_functions, utils_webengine, utils_filesdirs

from PyQt5 import QtCore, QtWidgets, QtGui
from PyQt5 import QtPrintSupport



# variables globales pour savoir si ça marche :
PDF_GENERATED = False
PRINT_WEBVIEW = None



def htmlToPdf(main, htmlFileName, pdfFileName, orientation='Portrait'):
    """
    Création d'un fichier pdf. On utilise un WebEngineView.
    """
    if orientation != 'Portrait':
        orientation = 'Landscape'

    def convertItWebKit():
        global PDF_GENERATED
        PRINT_WEBVIEW.print_(printer)
        PDF_GENERATED = True

    def convertItWebEngine():
        #PRINT_WEBVIEW.page().print(printer, printingFinished)
        pageLayout = QtGui.QPageLayout()
        pageLayout.setPageSize(QtGui.QPageSize(QtGui.QPageSize.A4))
        if orientation != 'Portrait':
            pageLayout.setOrientation(QtGui.QPageLayout.Landscape)
        PRINT_WEBVIEW.page().printToPdf(pdfFileName, pageLayout)

    def printingFinished(ok=None):
        global PDF_GENERATED
        PDF_GENERATED = True

    global PDF_GENERATED, PRINT_WEBVIEW
    PDF_GENERATED = False

    PRINT_WEBVIEW = utils_webengine.MyWebEngineView(
        main, linksInBrowser=True)

    if utils_webengine.WEB_ENGINE == 'WEBENGINE':
        PRINT_WEBVIEW.page().pdfPrintingFinished.connect(printingFinished)
        PRINT_WEBVIEW.loadFinished.connect(convertItWebEngine)
    else:
        printer = QtPrintSupport.QPrinter()
        printer.setPageSize(QtPrintSupport.QPrinter.A4)
        printer.setOutputFormat(QtPrintSupport.QPrinter.PdfFormat)
        if orientation == 'Portrait':
            printer.setOrientation(QtPrintSupport.QPrinter.Portrait)
        else:
            printer.setOrientation(QtPrintSupport.QPrinter.Landscape)
        printer.setOutputFileName(pdfFileName)
        PRINT_WEBVIEW.loadFinished.connect(convertItWebKit)

    url = QtCore.QUrl().fromLocalFile(htmlFileName)
    PRINT_WEBVIEW.load(url)

    while not(PDF_GENERATED):
        QtWidgets.QApplication.processEvents()
    del(PRINT_WEBVIEW)
    PRINT_WEBVIEW = None
    return True


class PDFConfigDlg(QtWidgets.QDialog):
    """
    Dialogue pour configurer le fichier PDF
    """
    def __init__(self, parent=None, initialValues={'notes': False, }, fileNamePdf=''):
        super(PDFConfigDlg, self).__init__(parent)

        self.main = parent
        # le titre de la fenêtre :
        titleText = QtWidgets.QApplication.translate(
            'main', 'PDF export configuration')
        # 2 textes utilisés plusieurs fois :
        yesText = QtWidgets.QApplication.translate(
            'main', 'YES')
        noText = QtWidgets.QApplication.translate(
            'main', 'NO')

        # explications :
        widget = utils_webengine.MyWebEngineView(self)
        container = QtWidgets.QAbstractScrollArea()
        vBoxLayout = QtWidgets.QVBoxLayout()
        vBoxLayout.addWidget(widget)
        container.setLayout(vBoxLayout)
        mdFile = utils_functions.doLocale(
            self.main.locale, 'translations/helpPDF', '.md')
        outFileName = utils_filesdirs.md2html(self.main, mdFile)
        url = QtCore.QUrl().fromLocalFile(outFileName)
        widget.load(url)

        # impression ou non des notes :
        text = QtWidgets.QApplication.translate(
            'main', 'Print the notes')
        notesGroupBox = QtWidgets.QGroupBox(text)
        self.withNotes = QtWidgets.QRadioButton(yesText)
        radio2 = QtWidgets.QRadioButton(noText)
        self.withNotes.setChecked(True)
        vbox = QtWidgets.QVBoxLayout()
        vbox.addWidget(self.withNotes)
        vbox.addWidget(radio2)
        vbox.addStretch(1)
        notesGroupBox.setLayout(vbox)

        # ouvrir le fichier _temp.html :
        text = QtWidgets.QApplication.translate(
            'main', 'Open the html file')
        htmlGroupBox = QtWidgets.QGroupBox(text)
        self.openHtml = QtWidgets.QRadioButton(yesText)
        radio2 = QtWidgets.QRadioButton(noText)
        radio2.setChecked(True)
        vbox = QtWidgets.QVBoxLayout()
        vbox.addWidget(self.openHtml)
        vbox.addWidget(radio2)
        vbox.addStretch(1)
        htmlGroupBox.setLayout(vbox)

        # créer le fichier PDF :
        text = QtWidgets.QApplication.translate(
            'main', 'Create the PDF file')
        pdfGroupBox = QtWidgets.QGroupBox(text)
        self.createPDF = QtWidgets.QRadioButton(yesText)
        radio2 = QtWidgets.QRadioButton(noText)
        self.createPDF.setChecked(True)
        vbox = QtWidgets.QVBoxLayout()
        vbox.addWidget(self.createPDF)
        vbox.addWidget(radio2)
        vbox.addStretch(1)
        pdfGroupBox.setLayout(vbox)

        # nom du fichier PDF :
        text = QtWidgets.QApplication.translate(
            'main', 'PDF file name')
        pdfFileNameGroupBox = QtWidgets.QGroupBox(text)
        self.pdfFileNameEdit = QtWidgets.QLineEdit()
        self.pdfFileNameEdit.setText(fileNamePdf)
        changeFileNameButton = QtWidgets.QPushButton(
            utils.doIcon('document-save'), 
            QtWidgets.QApplication.translate('main', 'Change'))
        changeFileNameButton.clicked.connect(self.doChangeFileName)
        hbox = QtWidgets.QHBoxLayout()
        hbox.addWidget(self.pdfFileNameEdit)
        hbox.addWidget(changeFileNameButton)
        #hbox.addStretch(1)
        pdfFileNameGroupBox.setLayout(hbox)

        # boutons :
        okButton = QtWidgets.QPushButton(
            utils.doIcon('dialog-ok-apply'), 
            QtWidgets.QApplication.translate('main', 'Ok'))
        okButton.clicked.connect(self.accept)
        cancelButton = QtWidgets.QPushButton(
            utils.doIcon('dialog-cancel'), 
            QtWidgets.QApplication.translate('main', 'Cancel'))
        cancelButton.clicked.connect(self.close)
        buttonLayout = QtWidgets.QHBoxLayout()
        buttonLayout.addStretch(1)
        buttonLayout.addWidget(okButton)
        buttonLayout.addWidget(cancelButton)

        # mise en place :
        hLayout = QtWidgets.QHBoxLayout()
        hLayout.addWidget(notesGroupBox)
        hLayout.addWidget(htmlGroupBox)
        hLayout.addWidget(pdfGroupBox)

        mainLayout = QtWidgets.QVBoxLayout()
        mainLayout.addWidget(container)
        mainLayout.addLayout(hLayout)
        mainLayout.addWidget(pdfFileNameGroupBox)
        mainLayout.addStretch(1)
        mainLayout.addLayout(buttonLayout)

        self.setLayout(mainLayout)
        self.setWindowTitle(titleText)

    def doChangeFileName(self):
        pdfTitle = QtWidgets.QApplication.translate(
            'main', 'pdf File')
        proposedName = self.pdfFileNameEdit.text()
        pdfExt = QtWidgets.QApplication.translate(
            'main', 'pdf files (*.pdf)')
        fileName = QtWidgets.QFileDialog.getSaveFileName(
            self, pdfTitle, proposedName, pdfExt)
        if isinstance(fileName, tuple):
            fileName = fileName[0]
        if fileName == '':
            return
        self.pdfFileNameEdit.setText(fileName)


















