#!/usr/bin/python3
# -*- coding: utf-8 -*-

from PyQt6.QtWidgets import QApplication, QInputDialog, QFileDialog, QMessageBox
import pyqtgraph.exporters
from .doubleplotwidget import DoublePlotWidget
import re
from subprocess import run
import tempfile

licence = {}
licence['en'] = """
    phPLot.py

    this file is part of the package pyacidobasic version %s:

    a program to simulate acido-basic equilibria

    Copyright (C) 2010-2013 Georges Khaznadar <georgesk@debian.org>
    Copyright (C) 2024 philippe DALET <philippe.dalet@gmail.com>

    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/>.
"""

class phPlot(DoublePlotWidget):
    exportNo = 1

    def __init__(self, *args, **kw):
        DoublePlotWidget.__init__(self, *args, **kw)
        return

    def getFileName(self, fichier, ext, filtre):
        """
        Renvoie un nom de fichier à ouvrir pour un enregistrement
        @param fichier une proposition initiale pour le nom du fichier
        @param nb numero à inscrire dans le nom de fichier
        @param ext extension du nom de fichier
        @param filtre filtre les noms de fichiers visibles
        @result le nom du fichier choisi
        """
        msg = 'Nom du fichier à exporter'
        fichier = f"{fichier}{self.exportNo:03d}.{ext}"
        reponse = QFileDialog.getSaveFileName(self, msg, fichier, filtre)
        if len(reponse) :
            fichier = reponse[0]
        try:
            self.exportNo = int(re.compile('.*([0-9]).*').match(fichier).group(1))+1
        except ValueError:
            self.exportNo = 1
        return fichier

    def exportSVG(self, fileName=""):
        if not fileName:
            fileName = self.getFileName(
                'graphe', 'svg', 'Documents SVG (*.svg)')
        if fileName:
            exporter = pyqtgraph.exporters.SVGExporter(self.plotItem)
            exporter.export(fileName)

    def exportPDF(self):
        fileName = self.getFileName('graphe', 'pdf', 'Documents PDF (*.pdf)')
        if fileName:
            try:
                with tempfile.NamedTemporaryFile(suffix=".svg") as outfile:
                    self.exportSVG(fileName = outfile.name)
                    run(f"svg2pdf -o {fileName} {outfile.name}", shell=True)
            except Exception as e:
                QMessageBox.warning(
                    self,
                    QApplication.translate("pyacidobasic", "Message about the bug"),
                    QApplication.translate("pyacidobasic", f"Error: {e}"))
        return

    def exportJPG(self):
        fileName = self.getFileName('graphe', 'jpg', 'Images JPEG (*.jpg)')
        if fileName:
            exporter = pyqtgraph.exporters.ImageExporter(self.plotItem)
            try:
                exporter.export(fileName)
            except Exception as e:
                QMessageBox.warning(
                    self, QApplication.translate("pyacidobasic",
                                                 "Message about the bug"),
                    QApplication.translate("pyacidobasic",
                                           f"Error: {e}")
                    )
        return

    def newTitle(self):
        title = QInputDialog.getText(self, "Titre",
                                           "Indiquer le titre à afficher sur \
                                           le graphique")
        if title[1]:
            self.setTitle(title[0])
