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

__author__ = 'wanger'
__date__ = '2024-08-27'
__copyright__ = '(C) 2024 by siwei'
__revision__ = '1.0'

import time

from processing.tools.GeoServer.Geoserver import Geoserver
from processing.tools.QGS.QgsProjectUtils import QgsProjectUtils
from processing.tools.FileUtils import getInputFileName
from processing.tools.StringUtils import getUUID
from processing.tools.PostgreSQL.PostgreSQL import PostgreSQL
from qgis.PyQt.QtCore import NULL


class GeoService:
    def __init__(
            self
    ):
        print("---GeoService init---")

    def publishGeoService(self, parameters, context, feedback, commands, zymlbsm, layer_group_join, raster_file):
        print(parameters)
        print(commands)
        # server_name = parameters.get("Server_NAME").encode("gbk")  # 服务名称
        geoserver_layer_name = ""
        server_name = parameters.get("Server_NAME")  # 服务名称
        all_vector_layers = []
        geoserverurl = parameters.get("GeoServer_URI")
        GeoServerConfig = {
            "uri": geoserverurl,
            "username": parameters.get("GeoServer_USERNAME"),
            "password": parameters.get("GeoServer_PASSWORD"),
            "workspace": parameters.get("GeoServer_WORKSPACE"),
            "caching_start": parameters.get("GeoServer_Caching_Start"),
            "caching_stop": parameters.get("GeoServer_Caching_Stop"),
            "style": "",
            "cachescheme": "WebMercatorQuadx2",
            "servertype": "geoserver",
            "servicetype": "wmts" if parameters.get("GeoServer_Caching") == True else "wms",
            "serviceurl": f'{geoserverurl}/gwc/service/wmts' if parameters.get(
                "GeoServer_Caching") == True else f'{geoserverurl}/wms',
        }
        geoserver = Geoserver(GeoServerConfig["uri"], username=GeoServerConfig["username"],
                              password=GeoServerConfig["password"])
        # 创建工作空间
        # geoserver.create_workspace(workspace=GeoServerConfig["workspace"])
        # GeoServer服务发布相关信息存储
        service_sjy = []
        # 判断是postgis
        if parameters.get("TABLE") is not None and parameters.get("TABLE") != "":
            DataSourceConfig = {
                "table": parameters.get("TABLE"),
                "schema": parameters.get("SCHEMA")
            }
            # 删除datastore
            geoserver.delete_featurestore(featurestore_name=DataSourceConfig["table"],
                                          workspace=GeoServerConfig["workspace"])
            geoserver.create_featurestore(store_name=DataSourceConfig["table"],
                                          workspace=GeoServerConfig["workspace"], db=commands[2],
                                          host=commands[0],
                                          pg_user=commands[3], pg_password=commands[4],
                                          schema=DataSourceConfig["schema"])
            geoserver.publish_featurestore(workspace=GeoServerConfig["workspace"],
                                           store_name=DataSourceConfig["table"], pg_table=DataSourceConfig["table"])
            # 判断是否切片
            if parameters.get("GeoServer_Caching") == True:
                geoserver.caching_layer(layer_name=(GeoServerConfig["workspace"] + ":" + DataSourceConfig["table"]),
                                        zoom_start=GeoServerConfig["caching_start"],
                                        zoom_stop=GeoServerConfig["caching_stop"], auto_seed=True)
        elif parameters.get("INPUTFILE") != NULL and parameters.get("INPUTFILE") != "":  # QGS工程文件
            print("========QGS工程文件=========")
            qgsfile = parameters.get("INPUTFILE")
            qgsProjectUtils = QgsProjectUtils(qgsfile)
            print("==============QGS工程文件读取完成=========")
            layers = qgsProjectUtils.getLayersSourceAndSld()
            print("==============QGS工程文件信息读取完成=========")
            for layername in layers:
                print(layername)
                all_vector_layers.append(layername)
                layer = layers[layername]
                if len(layers) == 1:
                    geoserver_layer_name = layername
                # 当前图层名称配置
                # cur_layer_name = server_name
                # if len(layers) > 1:
                #     cur_layer_name = layername
                # 删除style
                # geoserver.delete_style(style_name=cur_layer_name, workspace=GeoServerConfig["workspace"])
                # style样式
                style_uid = layername + getUUID()
                # 上传sld样式
                geoserver.upload_style(path=layer["sld"], workspace=GeoServerConfig["workspace"], name=style_uid)
                if layer["sourcetype"] == "db":
                    service_sjy.append(f'{layer["schema"]}.{layer["table"]}')
                    print(layer)
                    # 删除datastore
                    geoserver.delete_featurestore(featurestore_name=layer["table"],
                                                  workspace=GeoServerConfig["workspace"])
                    geoserver.create_featurestore(store_name=layer["table"],
                                                  workspace=GeoServerConfig["workspace"], db=layer["dbname"],
                                                  host=layer["host"],
                                                  pg_user=layer["user"], pg_password=layer["password"],
                                                  schema=layer["schema"])
                    geoserver.publish_featurestore(workspace=GeoServerConfig["workspace"],
                                                   store_name=layer["table"],
                                                   pg_table=layer["table"])
                    geoserver.publish_style(layer_name=layer["table"], style_name=style_uid,
                                            workspace=GeoServerConfig["workspace"])
                elif layer["sourcetype"] == "file":
                    geoserver.delete_featurestore(featurestore_name=layername,
                                                  workspace=GeoServerConfig["workspace"])
                    geoserver.create_datastore(path=layer["path"], name=layername,
                                               workspace=GeoServerConfig["workspace"])
                    geoserver.publish_featurestore(workspace=GeoServerConfig["workspace"], store_name=layername,
                                                   pg_table=layername)
                    geoserver.publish_style(layer_name=layername, style_name=style_uid,
                                            workspace=GeoServerConfig["workspace"])
                # 判断是否切片
                if parameters.get("GeoServer_Caching") == True and len(layers) == 1:
                    geoserver.caching_layer(
                        layer_name=(GeoServerConfig["workspace"] + ":" + layername),
                        zoom_start=GeoServerConfig["caching_start"],
                        zoom_stop=GeoServerConfig["caching_stop"], auto_seed=True)

            # 图层组新增 QGS模板图层大于1则发布图层组
            if len(layers) > 1:
                print("======创建图层组======")
                servername = qgsProjectUtils.getQgsBaseName()
                geoserver_layer_name = servername
                layernames = []
                for layername in layers:
                    layernames.append(layername)
                # 图层组顺组为倒序
                layerarr = layernames[::-1]
                geoserver.delete_layergroup(
                    layergroup_name=servername,
                    workspace=GeoServerConfig["workspace"],
                )
                geoserver.create_layergroup(
                    name=servername,
                    mode="single",
                    title=servername,
                    abstract_text=servername,
                    layers=layerarr,
                    workspace=GeoServerConfig["workspace"],
                    keywords=["list", "of", "keywords"]
                )
                # 判断是否切片
                if parameters.get("GeoServer_Caching") == True:
                    geoserver.caching_layer(
                        layer_name=(GeoServerConfig["workspace"] + ":" + servername),
                        zoom_start=GeoServerConfig["caching_start"],
                        zoom_stop=GeoServerConfig["caching_stop"], auto_seed=True)
        elif parameters.get("INPUTRASTER") != NULL and parameters.get("INPUTRASTER") != "":  # 栅格数据
            all_vector_layers.append(server_name)
            raster = raster_file
            # 删除datastore
            geoserver.delete_featurestore(featurestore_name=server_name,
                                          workspace=GeoServerConfig["workspace"])
            geoserver.create_coveragestore(layer_name=server_name, path=raster, workspace=GeoServerConfig["workspace"])
            geoserver.publish_style(layer_name=server_name, style_name='raster', workspace=GeoServerConfig["workspace"])
            # 判断是否切片
            if parameters.get("GeoServer_Caching") == True:
                geoserver.caching_layer(layer_name=(GeoServerConfig["workspace"] + ":" + server_name),
                                        zoom_start=GeoServerConfig["caching_start"],
                                        zoom_stop=GeoServerConfig["caching_stop"], auto_seed=True)
        # 创建或加入图层组
        layer_group_add_name = parameters.get("LAYER_GROUP_ADD")
        layergroupname = ''
        if layer_group_add_name is not None and layer_group_add_name != "":
            layergroupname = layer_group_add_name
            geoserver_layer_name = layer_group_add_name
            geoserver.delete_layergroup(
                layergroup_name=layer_group_add_name,
                workspace=GeoServerConfig["workspace"],
            )
            geoserver.create_layergroup(
                name=layer_group_add_name,
                mode="single",
                title=layer_group_add_name,
                abstract_text=layer_group_add_name,
                layers=all_vector_layers,
                workspace=GeoServerConfig["workspace"],
                keywords=["list", "of", "keywords"]
            )
            # 判断是否切片
            if parameters.get("GeoServer_Caching") == True:
                geoserver.caching_layer(
                    layer_name=(GeoServerConfig["workspace"] + ":" + layer_group_add_name),
                    zoom_start=GeoServerConfig["caching_start"],
                    zoom_stop=GeoServerConfig["caching_stop"], auto_seed=True)
        elif layer_group_join is not None and layer_group_join != "":
            geoserver_layer_name = layer_group_join
            layergroupname = layer_group_join
            for layer in all_vector_layers:
                geoserver.add_layer_to_layergroup(
                    layergroup_name=layer_group_join,
                    layergroup_workspace=GeoServerConfig["workspace"],
                    layer_name=layer,
                    layer_workspace=GeoServerConfig["workspace"]
                )
            # 判断是否切片
            if parameters.get("GeoServer_Caching") == True:
                geoserver.caching_layer(
                    layer_name=(GeoServerConfig["workspace"] + ":" + layer_group_add_name),
                    zoom_start=GeoServerConfig["caching_start"],
                    zoom_stop=GeoServerConfig["caching_stop"], auto_seed=True)
        result = {
            "Publish_Status": "Success"
        }
        # 数据服务发布信息插入
        pgconn = PostgreSQL(schema='base')
        pgconn.insertVectorServer(id=getUUID(), fwqlx=GeoServerConfig["servertype"], sjy=','.join(service_sjy),
                                  fwlx=GeoServerConfig["servicetype"], fwdz=GeoServerConfig["serviceurl"],
                                  fwmc=server_name, layername=geoserver_layer_name,
                                  fwgzkj=GeoServerConfig["workspace"], fwys=GeoServerConfig["style"],
                                  qpfa=GeoServerConfig["cachescheme"], zymlbsm=zymlbsm, layergroup=layergroupname,
                                  zoommin=GeoServerConfig["caching_start"], zoommax=GeoServerConfig["caching_stop"])
        # 是否将创建的图层组也插入一条新的记录
        if layer_group_add_name is not None and layer_group_add_name != "":
            pgconn.insertVectorServer(id=getUUID(), fwqlx=GeoServerConfig["servertype"], sjy=','.join(service_sjy),
                                      fwlx=GeoServerConfig["servicetype"], fwdz=GeoServerConfig["serviceurl"],
                                      fwmc=layergroupname, layername=geoserver_layer_name,
                                      fwgzkj=GeoServerConfig["workspace"], fwys=GeoServerConfig["style"],
                                      qpfa=GeoServerConfig["cachescheme"], zymlbsm=zymlbsm, layergroup=layergroupname,
                                      zoommin=GeoServerConfig["caching_start"], zoommax=GeoServerConfig["caching_stop"])

        if layer_group_join is None or layer_group_join == "":
            pgconn.insertPortalZymlServer(id=getUUID(), fwqlx=GeoServerConfig["servertype"], sjy=','.join(service_sjy),
                                          fwlx=GeoServerConfig["servicetype"], fwdz=GeoServerConfig["serviceurl"],
                                          fwmc=server_name, layername=geoserver_layer_name,
                                          fwgzkj=GeoServerConfig["workspace"], fwys=GeoServerConfig["style"],
                                          qpfa=GeoServerConfig["cachescheme"], zymlbsm=zymlbsm,
                                          layergroup=layergroupname,
                                          zoommin=GeoServerConfig["caching_start"],
                                          zoommax=GeoServerConfig["caching_stop"])

        pgconn.close()
        return result
