"""
***************************************************************************
    GdalAlgorithmProvider.py
    ---------------------
    Date                 : August 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__ = 'August 2012'
__copyright__ = '(C) 2012, Victor Olaya'

import os

from PyQt5.QtGui import QIcon
from osgeo import gdal

from qgis.PyQt.QtCore import QCoreApplication
from qgis.core import (QgsApplication,
                       QgsProcessingProvider,
                       QgsRuntimeProfiler)
from processing.core.ProcessingConfig import ProcessingConfig, Setting
from .GdalUtils import GdalUtils

from .AssignProjection import AssignProjection
from .aspect import aspect
from .buildvrt import buildvrt
from .ClipRasterByExtent import ClipRasterByExtent
from .ClipRasterByMask import ClipRasterByMask
from .ColorRelief import ColorRelief
from .contour import contour, contour_polygon
from .Datasources2Vrt import Datasources2Vrt
from .fillnodata import fillnodata
from .gdalinfo import gdalinfo
from .gdal2tiles import gdal2tiles
from .gdal2xyz import gdal2xyz
from .gdaladdo import gdaladdo
from .gdalcalc import gdalcalc
from .gdaltindex import gdaltindex
from .GridAverage import GridAverage
from .GridDataMetrics import GridDataMetrics
from .GridInverseDistance import GridInverseDistance
from .GridInverseDistanceNearestNeighbor import GridInverseDistanceNearestNeighbor
from .GridLinear import GridLinear
from .GridNearestNeighbor import GridNearestNeighbor
from .hillshade import hillshade
from .merge import merge
from .nearblack import nearblack
from .pct2rgb import pct2rgb
from .polygonize import polygonize
from .proximity import proximity
from .rasterize import rasterize
from .rearrange_bands import rearrange_bands
from .retile import retile
from .rgb2pct import rgb2pct
from .roughness import roughness
from .sieve import sieve
from .slope import slope
from .translate import translate
from .tpi import tpi
from .tri import tri
from .warp import warp
from .pansharp import pansharp
from .rasterize_over_fixed_value import rasterize_over_fixed_value
from .viewshed import viewshed

from .extractprojection import ExtractProjection
from .rasterize_over import rasterize_over

from .Buffer import Buffer
from .ClipVectorByExtent import ClipVectorByExtent
from .ClipVectorByMask import ClipVectorByMask
from .Dissolve import Dissolve
from .ExecuteSql import ExecuteSql
from .OffsetCurve import OffsetCurve
from .ogr2ogr import ogr2ogr
from .ogrinfo import ogrinfo
from .OgrToPostGis import OgrToPostGis
from .ogr2ogrtopostgislist import Ogr2OgrToPostGisList
from .rastertopostgislist import Ogr2PostGisList
from .postgistogeoserver import Postgistogeoserver
from .postgisupdate import Postgisupdate
from .postgisrestore import Postgisrestore
from .OneSideBuffer import OneSideBuffer
# from .spotfileupload import SpotfileUpload
# from .spotfiledownload import SpotfileDownload
# from .spotfiledelete import SpotfileDelete
from .PointsAlongLines import PointsAlongLines
from .ExportVectorByMask import ExportVectorByMask
from .ExportRasterByMask import ExportRasterByMask
from .gdbtopostgislist import GdbToPostGisList
from .VectorProject import VectorProject
from .LicenseMake import LicenseMake
from .Topology.A00 import A00
from .Topology.A01 import A01
from .Topology.A02 import A02
from .Topology.A03 import A03
from .Topology.A04 import A04
from .Topology.A05 import A05
from .Topology.P00 import P00
from .Topology.P01 import P01
from .Topology.L00 import L00
from .Topology.L01 import L01
from .Topology.L02 import L02
from .Topology.L03 import L03
from .Topology.L04 import L04
from .Topology.L05 import L05
from .Topology.L06 import L06
from .Topology.L07 import L07
from .Topology.L08 import L08
from .Topology.L09 import L09
from .Topology.L10 import L10
from .Topology.PP01 import PP01
from .Topology.PP02 import PP02
from .Topology.PL01 import PL01
from .Topology.PL02 import PL02
from .Topology.PA01 import PA01
from .Topology.PA02 import PA02
from .Topology.PA03 import PA03
from .Topology.LP01 import LP01
from .Topology.LL01 import LL01
from .Topology.LL02 import LL02
from .Topology.LL03 import LL03
from .Topology.LL04 import LL04
from .Topology.LA01 import LA01
from .Topology.LA02 import LA02
from .Topology.LA03 import LA03
from .Topology.AP01 import AP01
from .Topology.AP02 import AP02
from .Topology.AL01 import AL01
from .Topology.AA01 import AA01
from .Topology.AA02 import AA02
from .Topology.AA03 import AA03
from .Topology.AA04 import AA04
from .Topology.AA05 import AA05
from .topologycheck import TopologyCheck

# from .ogr2ogrtabletopostgislist import Ogr2OgrTableToPostGisList

pluginPath = os.path.normpath(os.path.join(
    os.path.split(os.path.dirname(__file__))[0], os.pardir))


class GdalAlgorithmProvider(QgsProcessingProvider):

    def __init__(self):
        super().__init__()
        self.algs = []
        QgsApplication.processingRegistry().addAlgorithmAlias('qgis:buildvirtualvector', 'gdal:buildvirtualvector')

    def load(self):
        with QgsRuntimeProfiler.profile('GDAL Provider'):
            ProcessingConfig.settingIcons[self.name()] = self.icon()
            ProcessingConfig.addSetting(Setting(self.name(), 'ACTIVATE_GDAL',
                                                self.tr('Activate'), True))
            ProcessingConfig.readSettings()
            self.refreshAlgorithms()
        return True

    def unload(self):
        ProcessingConfig.removeSetting('ACTIVATE_GDAL')

    def isActive(self):
        return ProcessingConfig.getSetting('ACTIVATE_GDAL')

    def setActive(self, active):
        ProcessingConfig.setSettingValue('ACTIVATE_GDAL', active)

    def name(self):
        return '数管工具集'

    def longName(self):
        version = GdalUtils.readableVersion()
        return f'数管工具集 ({version})'

    def id(self):
        return 'gdal'

    def helpId(self):
        return 'gdal'

    def icon(self):
        return QIcon(os.path.join(pluginPath, 'images', 'dbms', 'tools.png'))
        # return QgsApplication.getThemeIcon("/providerGdal.svg")

    def svgIconPath(self):
        return os.path.join(pluginPath, 'images', 'dbms', 'tools.png')
        # return QgsApplication.iconPath("providerGdal.svg")

    def loadAlgorithms(self):
        self.algs = [
            AssignProjection(),
            aspect(),
            buildvrt(),
            ClipRasterByExtent(),
            ClipRasterByMask(),
            ColorRelief(),
            contour(),
            contour_polygon(),
            Datasources2Vrt(),
            fillnodata(),
            gdalinfo(),
            gdal2tiles(),
            gdal2xyz(),
            gdaladdo(),
            gdalcalc(),
            gdaltindex(),
            GridAverage(),
            GridDataMetrics(),
            GridInverseDistance(),
            GridInverseDistanceNearestNeighbor(),
            GridLinear(),
            GridNearestNeighbor(),
            hillshade(),
            merge(),
            nearblack(),
            pct2rgb(),
            polygonize(),
            proximity(),
            rasterize(),
            rearrange_bands(),
            retile(),
            rgb2pct(),
            roughness(),
            sieve(),
            slope(),
            translate(),
            tpi(),
            tri(),
            warp(),
            pansharp(),
            # rasterize(),
            ExtractProjection(),
            rasterize_over(),
            rasterize_over_fixed_value(),
            # ----- OGR tools -----
            Buffer(),
            ClipVectorByExtent(),
            ClipVectorByMask(),
            Dissolve(),
            ExecuteSql(),
            OffsetCurve(),
            ogr2ogr(),
            ogrinfo(),
            OgrToPostGis(),
            Ogr2OgrToPostGisList(),
            Ogr2PostGisList(),
            Postgistogeoserver(),
            OneSideBuffer(),
            PointsAlongLines(),
            Postgisupdate(),
            Postgisrestore(),
            # SpotfileUpload(),
            # SpotfileDownload(),
            # SpotfileDelete(),
            ExportVectorByMask(),
            GdbToPostGisList(),
            ExportRasterByMask(),
            VectorProject(),
            LicenseMake(),
            # TopologyCheck(),
            A00(),
            A01(),
            A02(),
            A03(),
            A04(),
            A05(),
            P00(),
            P01(),
            L00(),
            L01(),
            L02(),
            L03(),
            L04(),
            L05(),
            L06(),
            L07(),
            L08(),
            L09(),
            L10(),
            PP01(),
            PP02(),
            PL01(),
            PL02(),
            PA01(),
            PA02(),
            PA03(),
            LP01(),
            LL01(),
            LL02(),
            LL03(),
            LL04(),
            LA01(),
            LA02(),
            LA03(),
            AP01(),
            AP02(),
            AL01(),
            AA01(),
            AA02(),
            AA03(),
            AA04(),
            AA05()
            # Ogr2OgrTableToPostGisList(),
        ]

        if int(gdal.VersionInfo()) > 3010000:
            self.algs.append(viewshed())

        for a in self.algs:
            self.addAlgorithm(a)

    def supportedOutputRasterLayerExtensions(self):
        return GdalUtils.getSupportedOutputRasterExtensions()

    def supportsNonFileBasedOutput(self):
        """
        GDAL Provider doesn't support non file based outputs
        """
        return False

    def tr(self, string, context=''):
        if context == '':
            context = 'GdalAlgorithmProvider'
        return QCoreApplication.translate(context, string)
