# -*- coding: utf-8 -*-
import subprocess
import os
import sys
import stat
import processing
import gc

"""
/***************************************************************************
 Networks
                                 A QGIS plugin
 Networks
 Generated by Plugin Builder: http://g-sherman.github.io/Qgis-Plugin-Builder/
                              -------------------
        begin                : 2018-02-26
        copyright            : (C) 2018 by Patrick Palmier
        email                : patrick.palmier@cerema.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 2 of the License, or     *
 *   (at your option) any later version.                                   *
 *                                                                         *
 ***************************************************************************/
"""

__author__ = 'Patrick Palmier'
__date__ = '2018-02-26'
__copyright__ = '(C) 2018 by Patrick Palmier'

__revision__ = '$Format:%H$'

from qgis.PyQt.QtCore import QCoreApplication, QVariant
from qgis.core import *
from qgis.utils import *
from qgis.core import (QgsProcessing,
                       QgsFeatureSink,
                       QgsProcessingAlgorithm,
                       QgsProcessingParameterFile,
                       QgsProcessingParameterFileDestination,
                       QgsProcessingParameterBoolean)

class CalculMusliw(QgsProcessingAlgorithm):

    RESEAU = 'RESEAU'
    MATRICE = 'MATRICE'
    PARAMETRES = 'PARAMETRES'
    PENALITES = 'PENALTIES'
    SORTIE = 'SORTIE'
    DOWNLOAD = 'DOWNLOAD'
    WAIT = 'WAIT'

    def initAlgorithm(self, config):
        self.addParameter(
            QgsProcessingParameterFile(self.RESEAU, self.tr('Musliw network'))
        )
        self.addParameter(
            QgsProcessingParameterFile(self.MATRICE, self.tr('Musliw matrix'))
        )
        self.addParameter(
            QgsProcessingParameterFile(self.PARAMETRES, self.tr('Musliw parameters'))
        )
        self.addParameter(
            QgsProcessingParameterFile(
                self.PENALITES,
                self.tr('Musliw penalties'),
                optional=True
            )
        )
        self.addParameter(
            QgsProcessingParameterFileDestination(
                self.SORTIE,
                self.tr('Output'),
                "*.txt"
            )
        )
        self.addParameter(
            QgsProcessingParameterBoolean(
                self.DOWNLOAD,
                self.tr('Accept to download Musliw binary from Github'),
                False
            )
        )
        self.addParameter(
            QgsProcessingParameterBoolean(
                self.WAIT,
                self.tr('Force waiting the end of calculations'),
                True
            )
        )

    def processAlgorithm(self, parameters, context, feedback):
        reseau = self.parameterAsFile(parameters, self.RESEAU, context)
        matrice = self.parameterAsFile(parameters, self.MATRICE, context)
        parametres = self.parameterAsFile(parameters, self.PARAMETRES, context)
        penalites = self.parameterAsFile(parameters, self.PENALITES, context)
        sortie = os.path.splitext(self.parameterAsFileOutput(parameters, self.SORTIE, context))[0]
        download = self.parameterAsBool(parameters, self.DOWNLOAD, context)
        wait = self.parameterAsBool(parameters, self.WAIT, context)

        if download:
            feedback.setProgressText(self.tr("Downloading Muslic binary"))
            processing.run("native:filedownloader", {
                'URL': 'https://github.com/crocovert/muslic/raw/master/Muslic/bin/x64/Release/Muslic.exe',
                'OUTPUT': os.path.join(os.path.dirname(__file__), "Muslic.exe")
            })
            feedback.setProgressText(self.tr("Muslic downloaded successfully"))

        if sys.platform.startswith('win'):
            prog = os.path.join(os.path.dirname(__file__), "Muslic.exe")
            cmd = [prog, reseau, matrice, sortie, parametres]
        elif sys.platform.startswith('linux'):
            prog = os.path.join(os.path.dirname(__file__), "Muslic.exe")
            if os.path.exists(prog):
                st = os.stat(prog)
                os.chmod(prog, st.st_mode | stat.S_IEXEC)
            cmd = ["mono", prog, reseau, matrice, sortie, parametres]
        else:
            feedback.reportError(self.tr("Unsupported platform"), fatalError=True)
            return {}

        feedback.setProgressText(self.tr("Multimodal calculations... That could take some time"))

        if len(penalites or "") == 0:
            musliw_test = subprocess.Popen(cmd)  #nosec B603
        else:
            cmd.append(penalites)
            feedback.setProgressText(str(cmd))
            musliw_test = subprocess.Popen(cmd)  #nosec B603

        if wait:
            musliw_test.wait()

        gc.collect()
        return {'SORTIE': sortie}

    def name(self):
        return 'musliw_calculation'

    def displayName(self):
        return self.tr('Musliw computation')

    def group(self):
        return self.tr('Computations')

    def groupId(self):
        return 'Computations'

    def tr(self, string):
        return QCoreApplication.translate('CalculMusliw', string)

    def shortHelpString(self):
        return self.tr("""
        Perform a calculation of multimodal accessibility and routing
        Can download the Muslic.exe binary...
        """)

    def createInstance(self):
        return CalculMusliw()