import os

from qgis.utils import iface

from qgis.core import (
    QgsProcessing,
    QgsProcessingParameterFolderDestination,
    QgsProcessingParameterString,
    QgsProcessingParameterVectorLayer,
    Qgis,
)

from PreCourlis.core.precourlis_file import PreCourlisFileLine
from PreCourlis.lib.mascaret.mascaretgeo_file import MascaretGeoFile
from PreCourlis.processing.precourlis_algorithm import PreCourlisAlgorithm

"""
This algorithm export a Mascaret structured line layer to several .mob files
(.geo files renamed), one per layer.
"""


class ExportMobiliAlgorithm(PreCourlisAlgorithm):

    INPUT_PROFILES = "INPUT_PROFILES"
    REACH_NAME = "REACH_NAME"
    OUTPUT_FOLDER = "OUTPUT_FOLDER"

    def initAlgorithm(self, config):
        self.addParameter(
            QgsProcessingParameterVectorLayer(
                self.INPUT_PROFILES,
                self.tr("Profiles layer"),
                types=[QgsProcessing.TypeVectorLine],
                defaultValue=None,
            )
        )

        self.addParameter(
            QgsProcessingParameterString(
                self.REACH_NAME,
                self.tr("Reach name (default to Profiles layer name)"),
                optional=True,
            )
        )

        self.addParameter(
            QgsProcessingParameterFolderDestination(
                self.OUTPUT_FOLDER,
                self.tr("Output folder"),
            )
        )

    def checkParameterValues(self, parameters, context):
        ok, msg = super().checkParameterValues(parameters, context)
        if ok:
            input_layer = self.parameterAsVectorLayer(
                parameters, self.INPUT_PROFILES, context
            )
            reach_name = (
                self.parameterAsString(parameters, self.REACH_NAME, context)
                or input_layer.name()
            )
            if " " in reach_name:
                return False, self.tr("Reach name cannot contain spaces")

            # Checking that there is no more than 2 layers (+ zfond)
            precourlis_file = PreCourlisFileLine(input_layer)
            if len(precourlis_file.layers()) > 2:
                iface.messageBar().pushMessage(
                    self.tr("Warning"),
                    self.tr(
                        "Export Mobili: You're not supposed to have more than 3 z interfaces!"
                    ),
                    level=Qgis.Warning,
                )
        return ok, msg

    def processAlgorithm(self, parameters, context, feedback):
        input_layer = self.parameterAsVectorLayer(
            parameters, self.INPUT_PROFILES, context
        )
        reach_name = (
            self.parameterAsString(parameters, self.REACH_NAME, context)
            or input_layer.name()
        )
        output_folder_path = self.parameterAsFile(
            parameters, self.OUTPUT_FOLDER, context
        )

        # Create folder if not exists (default temporary folder)
        os.makedirs(output_folder_path, exist_ok=True)

        # First output only with zfond and no layer
        # and other ouputs for each interface/layer, one at a time with no zfond.
        precourlis_file = PreCourlisFileLine(input_layer)
        sedimental_layers_names = precourlis_file.layers()
        sedimental_layers_names.insert(0, "zfond")

        # Checking that there is no more than 2 layers (+ zfond)
        precourlis_file = PreCourlisFileLine(input_layer)
        if len(precourlis_file.layers()) > 2:
            feedback.reportError(
                self.tr("You're not supposed to have more than 3 z interfaces!")
            )

        for sedimental_layer_name in sedimental_layers_names:
            reach = precourlis_file.get_reach(reach_name, sedimental_layer_name)

            output_filename = os.path.join(
                output_folder_path, reach_name + "_" + sedimental_layer_name + ".geo"
            )

            output_file = MascaretGeoFile(output_filename, mode="write")
            output_file.has_ref = "ref" in os.path.splitext(output_folder_path)[1][1:]
            output_file.add_reach(reach)
            output_file.nlayers = len(precourlis_file.layers())
            output_file.save(output_filename)

            # Change file extension from .geo to .mob
            output_filename_with_mob_extension = os.path.join(
                output_folder_path, reach_name + "_" + sedimental_layer_name + ".mob"
            )
            os.rename(output_filename, output_filename_with_mob_extension)

        return {self.OUTPUT_FOLDER: output_folder_path}

    def name(self):
        return "export_mobili"

    def displayName(self):
        return self.tr("Export Mobili")

    def group(self):
        return self.tr("Export")

    def groupId(self):
        return "Export"

    def createInstance(self):
        return ExportMobiliAlgorithm()
