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

"""
***************************************************************************
    parameters.py
    ---------------------
    Date                 : April 2021
    Copyright            : (C) 2021 by René-Luc Dhont
    Email                : rldhont at gmail dot 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 2 of the License, or     *
*   (at your option) any later version.                                   *
*                                                                         *
***************************************************************************
"""

from processing.core.parameters import getParameterFromString

from ..Utils import ParamsR

from qgis.core import QgsProcessingParameterMapLayer, QgsProcessing


def create_parameter_from_string(s: str):
    """
    Tries to create an algorithm parameter from a line string.
    Handles standard Processing parameters as well as custom 'raster_or_polygon'.
    """
    # print(f"[DEBUG] create_parameter_from_string received: {s}") #debugtest

    # Specific case for custom parameter
    if s.lower().endswith("raster_or_polygon"):
        name = s.split("=")[0].replace("##", "").strip()
        description = ParamsR.create_descriptive_name(name)

        try:
            param = QgsProcessingParameterMapLayer(
                name,
                description,
                types=[
                    QgsProcessing.TypeVectorPolygon,
                    QgsProcessing.TypeRaster
                ]
            )
            # print(f"[DEBUG] Param créé : {param}") #debugtest
            return param
        except Exception as e:
            # print(f"[ERROR] Impossible de créer QgsProcessingParameterMapLayer: {e}") #debugtest
            param = QgsProcessingParameterFeatureSource(
                name,
                description,
                types=[QgsProcessing.TypeVectorPolygon]
            )
            # print(f"[DEBUG] Param fallback créé : {param}") #debugtest
            return param

    if not ("|" in s and s.startswith("QgsProcessingParameter")):
        s = ParamsR.upgrade_parameter_line(s)
        s = s.replace("enum literal", "enum")

    try:
        param = getParameterFromString(s, context="")
    except TypeError:
        param = getParameterFromString(s)

    return param
