"""
***************************************************************************
    VectorProject.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 QgsCoordinateReferenceSystem, 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 VectorProject(GdalAlgorithm):
    INPUT = 'INPUT'
    T_SRS = 'T_SRS'
    OUTPUT = 'OUTPUT'

    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('数据源')))
        crs = QgsCoordinateReferenceSystem("EPSG:4525")
        crs_parameter = QgsProcessingParameterCrs(self.T_SRS,
                                                  self.tr('输出坐标系'),
                                                  defaultValue=crs)
        self.addParameter(crs_parameter)

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

    def name(self):
        return 'vectorproject'

    def displayName(self):
        return self.tr('矢量数据重投影')

    def group(self):
        return self.tr('数据处理')

    def groupId(self):
        return 'datahandle'

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

    def commandName(self):
        return 'ogr2ogr'

    def getConsoleCommands(self, parameters, context, feedback, executing=True):
        inLayer, inLayerName = self.getOgrCompatibleSource(self.INPUT, parameters, context, feedback, executing)
        print(inLayer)
        print(inLayerName)
        outFile = self.parameterAsOutputLayer(parameters, self.OUTPUT, context)
        self.setOutputValue(self.OUTPUT, outFile)
        tsrs = GdalUtils.gdal_crs_string(self.parameterAsCrs(parameters, self.T_SRS, context))
        print(tsrs)
        output, outputFormat = GdalUtils.ogrConnectionStringAndFormat(outFile, context)
        print(output)
        arguments = [
            '--config',
            'SHAPE_ENCODING',
            '"GBK2312"',
            '-t_srs',
            tsrs,
            output,
            inLayer
        ]
        arguments = [
            '-lco',
            'ENCODING=UTF-8',
            '-t_srs',
            tsrs,
            output,
            inLayer
        ]

        if inLayer.__contains__("PG:"):
            arguments.append(inLayerName)

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