"""
***************************************************************************
    ExportVectorByMask.py
    ---------------------
    Date                 : November 2012
    Copyright            : (C) 2012 by Victor Olaya
    Email                : volayaf 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.                                   *
*                                                                         *
***************************************************************************
"""

__author__ = 'Victor Olaya'
__date__ = 'November 2012'
__copyright__ = '(C) 2012, Victor Olaya'

import os

from PyQt5.QtGui import QIcon

from qgis._core import QgsProcessingParameterCrs
from qgis.core import (QgsProcessing,
                       QgsProcessingAlgorithm,
                       QgsProcessingParameterDefinition,
                       QgsProcessingParameterString,
                       QgsProcessingParameterFeatureSource,
                       QgsProcessingParameterVectorDestination)
from processing.algs.gdal.GdalAlgorithm import GdalAlgorithm
from processing.algs.gdal.GdalUtils import GdalUtils

pluginPath = os.path.split(os.path.split(os.path.dirname(__file__))[0])[0]


class ExportVectorByMask(GdalAlgorithm):
    INPUT = 'INPUT'
    MASK = 'MASK'
    OPTIONS = 'OPTIONS'
    OUTPUT = 'OUTPUT'
    S_SRS = "S_SRS"
    T_SRS = "T_SRS"

    def __init__(self):
        super().__init__()

    def flags(self):
        return QgsProcessingAlgorithm.FlagSupportsBatch | QgsProcessingAlgorithm.FlagRequiresMatchingCrs  # cannot cancel!

    def initAlgorithm(self, config=None):
        self.addParameter(QgsProcessingParameterFeatureSource(self.INPUT,
                                                              self.tr('数据源')))
        self.addParameter(QgsProcessingParameterCrs(self.S_SRS, self.tr('数据源坐标系'), optional=True))
        self.addParameter(QgsProcessingParameterFeatureSource(self.MASK,
                                                              self.tr('导出的数据范围'),
                                                              [QgsProcessing.TypeVectorPolygon]))

        self.addParameter(QgsProcessingParameterCrs(self.T_SRS, self.tr('数据范围坐标系'), optional=True))

        options_param = QgsProcessingParameterString(self.OPTIONS,
                                                     self.tr('Additional creation options'),
                                                     defaultValue='',
                                                     optional=True)
        options_param.setFlags(options_param.flags() | QgsProcessingParameterDefinition.FlagAdvanced)
        # self.addParameter(options_param)

        self.addParameter(QgsProcessingParameterVectorDestination(self.OUTPUT,
                                                                  self.tr('导出位置')))

    def name(self):
        return 'vectorexport'

    def displayName(self):
        return self.tr('矢量数据分发')

    def group(self):
        return self.tr('数据分发')

    def groupId(self):
        return 'dataexport'

    def icon(self):
        return QIcon(os.path.join(pluginPath, 'images', 'dbms', 'export-vector.png'))

    def commandName(self):
        return 'ogr2ogr'

    def getConsoleCommands(self, parameters, context, feedback, executing=True):
        inLayer, inLayerName = self.getOgrCompatibleSource(self.INPUT, parameters, context, feedback, executing)
        maskLayer, maskLayerName = self.getOgrCompatibleSource(self.MASK, parameters, context, feedback, executing)
        options = self.parameterAsString(parameters, self.OPTIONS, context)
        outFile = self.parameterAsOutputLayer(parameters, self.OUTPUT, context)
        self.setOutputValue(self.OUTPUT, outFile)

        output, outputFormat = GdalUtils.ogrConnectionStringAndFormat(outFile, context)
        tsrs = self.parameterAsCrs(parameters, self.T_SRS, context)
        ssrs = self.parameterAsCrs(parameters, self.S_SRS, context)

        arguments = [
            # '--config',
            # 'SHAPE_ENCODING',
            # 'ISO-8859-1',
            '-lco',
            'ENCODING=UTF-8',
            # 'LCID=CHINESE_SIMPLIFIED',
            # 'CP=936',
            '-clipsrc',
            maskLayer,
            '-clipsrclayer',
            maskLayerName,
            output,
            inLayer,
            inLayerName,
        ]

        if tsrs.isValid():
            arguments.append('-t_srs')
            arguments.append(GdalUtils.gdal_crs_string(tsrs))
        if ssrs.isValid():
            arguments.append('-s_srs')
            arguments.append(GdalUtils.gdal_crs_string(ssrs))

        if options:
            arguments.append(options)

        if outputFormat:
            arguments.append(f'-f {outputFormat}')

        return [self.commandName(), GdalUtils.escapeAndJoin(arguments)]
