"""
This file is useful in Debian packages, to let users download some software
pieces which have non-free licenses.
"""

import sys, os, re
from PyQt5.QtWidgets import QDialog, QApplication, QMessageBox
from PyQt5 import QtCore
from ui_pampi_nonfree import Ui_Dialog
from subprocess import call, Popen, PIPE

nf = {}
nf["deployggb.js"] = {
    "URL": "https://gitlab.com/edleh/pampi/-/raw/master/pampi/presentations/assets/tools/GeoGebra/deployggb.js?inline=false",
    "location": "presentations/assets/tools/GeoGebra",
}

nf["Vis"] = {
    "URL": ["https://gitlab.com/edleh/pampi/-/raw/master/pampi/presentations/assets/tools/Vis/vis.min.js?inline=false",
            "https://gitlab.com/edleh/pampi/-/raw/master/pampi/presentations/assets/tools/Vis/vis.min.css?inline=false"],
    "location": ["presentations/assets/tools/Vis",
                 "presentations/assets/tools/Vis"],
}


class MonDialogue(QDialog, Ui_Dialog):
    def __init__(self, parent=None):
        super(MonDialogue, self).__init__(parent)
        self.setupUi(self)
        return

    def installable(self):
        install=[]
        if self.deployggbBox.isChecked():
            install.append("deployggb.js")
        if self.VisBox.isChecked():
            install.append("Vis")
        return install

    def download(self, key):
        urls = nf[key]["URL"]
        locations = nf[key]["location"]
        if type(urls) == str:
            urls=[urls]
        if type(locations) == str:
            locations = [locations]
        ddir = QtCore.QStandardPaths.standardLocations(
            QtCore.QStandardPaths.DocumentsLocation)
            
        for url, location in zip(urls, locations):
            m = re.match(r"^https?://.*/([^\?]*).*$", url)
            filename = m.group(1)
            target = os.path.join(ddir, location, filename)
            cmd = "wget {} -O {}".format(url, target)
            ret = call (cmd, shell=True)
            if ret == 0:
                QMessageBox.information(self, self.tr("Download OK"), self.tr("{} was successfully downloaded,\nto{}").format(filename, target))
            else:
                QMessageBox.warning(self, self.tr("Download Failed"), self.tr("{} is not downloaded").format(filename))
        return

if __name__ == "__main__":
    app = QApplication(sys.argv)
    locale = QtCore.QLocale.system().name()
    # recherche d'un i18n passé en argument
    # (par exemple LANG=fr_FR) :
    for arg in sys.argv:
        if arg.split('=')[0] == 'LANG':
            locale = arg.split('=')[1]
    # traduction de Qt (boutons des dialogues, etc) :
    qtTranslationsPath = QtCore.QLibraryInfo.location(
        QtCore.QLibraryInfo.TranslationsPath)
    qtTranslator = QtCore.QTranslator()
    if qtTranslator.load('qtbase_' + locale, qtTranslationsPath):
        app.installTranslator(qtTranslator)
    elif qtTranslator.load('qt_' + locale, qtTranslationsPath):
        app.installTranslator(qtTranslator)
    # traduction du logiciel :
    appLocalefile = 'pampi-nonfree_{}'.format(locale)
    appTranslator = QtCore.QTranslator()
    if appTranslator.load(appLocalefile, '.'):
        app.installTranslator(appTranslator)

    md = MonDialogue()
    md.show()
    OK = md.exec_()
    if OK:
        for i in md.installable():
            md.download(i)

