from qgis.PyQt.QtCore import (
  QT_TRANSLATE_NOOP, QVariant
  )
from qgis.core import (
  QgsProcessing,
  QgsProcessingParameterMultipleLayers,
  QgsProcessingParameterFeatureSink,
  QgsProcessingParameterBoolean,
  QgsProcessingParameterCrs,
  QgsWkbTypes
  )

from .initroad import initroad
from qgis import processing
import sys

class mergeroad(initroad):
  PARAMETERS = {                  
    "INPUT": {
      "ui_func": QgsProcessingParameterMultipleLayers,
      "ui_args":{
        "description": QT_TRANSLATE_NOOP("mergeroad","Building layers to merge"),
        "layerType": QgsProcessing.TypeVectorLine
      }
    },
    "TARGET_CRS": {
      "ui_func": QgsProcessingParameterCrs,
      "ui_args": {
        "description": QT_TRANSLATE_NOOP("mergeroad","Target CRS (Cartesian coordinates)")
      }
    },
    "KEEP_ATTRIBUTES": {
      "ui_func": QgsProcessingParameterBoolean,
      "ui_args":{
        "description" : QT_TRANSLATE_NOOP("mergeroad","Keep all attributes (or only the required fields)?"),
        "defaultValue": True
      }
    },
    "OUTPUT": {
      "ui_func": QgsProcessingParameterFeatureSink,
      "ui_args": {
        "description": QT_TRANSLATE_NOOP("mergeroad","Building" )
      }
    }
  }
  
  
  def processAlgorithm(self, parameters, context, feedback):
    
    target_crs = self.parameterAsCrs(parameters, "TARGET_CRS", context)
    # check whether the target CRS is x-y coordinates
    if target_crs.isGeographic() or target_crs.authid() == "EPSG:3857":
      sys.exit(self.tr("The Target CRS is NOT a Cartesian Coordinate System"))

    # initialize all the layers
    merge_layers = []
    for layer in self.parameterAsLayerList(parameters, "INPUT", context):

      # check whether the layer needs to be initialized          
      if layer.crs() != target_crs or any([required_fld not in layer.fields().names() for required_fld in self.FIELDS_REQUIRED]):
        merge_layers.append(
          processing.run(
            "hrisk:initroad",
            {
              "INPUT": layer,
              "TARGET_CRS": target_crs,
              "OVERWRITE": False,
              "OUTPUT": "TEMPORARY_OUTPUT"
            }
          )["OUTPUT"]
        )
      else:
        merge_layers.append(layer)
      
    # list up all the fields, if necessary
    for layer in merge_layers:
      self.setFieldsDict(
        parameters, context, feedback, 
        layer.fields(),
        overwrite = False
      )

    # define the feature sink
    (sink, dest_id) = self.parameterAsSink(
      parameters, "OUTPUT", context, 
      self.FIELDS_INIT, 
      QgsWkbTypes.LineString,
      target_crs
    )
    
    self.resetPk()
    
    # add all the features
    for layer in merge_layers:
      self.addFeaturesToSink(sink, dest_id, layer)
              
    return {"OUTPUT": dest_id}
  
  def createInstance(self):
    return mergeroad()

  def displayName(self):
    return self.tr("Merged Road")

  def group(self):
    return self.tr("Initialize features")

  def groupId(self):
    return "initfeature"

  def createInstance(self):
    return mergeroad()
