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

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

# 导入QGIS核心模块
from qgis.core import QgsProject


class QgsProjectUtils:
    def __init__(
            self,
            qgsfile: str
    ):
        self.project = QgsProject.instance()
        self.project.read(qgsfile)

    # 读取qgs文件中的图层列表
    def getLayersSourceAndSld(self):
        absolutepath = self.project.absolutePath()
        filename = self.project.baseName()
        result = {}
        print("absolutepath={};filename={}".format(absolutepath, filename))
        # 遍历所有图层名称
        for layerid in self.project.mapLayers():
            layer = self.project.mapLayer(layerid)
            layername = layer.name()
            source = layer.source()
            obj = {}
            if (source.__contains__("dbname")):
                obj = self.sourceToDBConfig(source)
            else:
                obj = self.sourceToFileConfig(source)
            # layer生成.sld样式文件
            sldpath = '{}\{}_{}.sld'.format(absolutepath, layer.name(), layer.geometryType().name.lower())
            layer.saveSldStyle(sldpath)
            obj["sld"] = sldpath
            result[layername] = obj
        return result

    #获取qgs模板名称
    def getQgsBaseName(self):
        return self.project.baseName()

    # 将数据库连接字符串转换成object
    def sourceToDBConfig(self, source):
        result = {
            "sourcetype": "db"
        }
        arr = source.split(" ")
        for attr in arr:
            if attr.__contains__("="):
                cur = attr.split("=")
                key = cur[0].replace("'", "")
                value = cur[1].replace("'", "").replace("\"", "")
                if key == "table":
                    result[key] = value.split(".")[1]
                    result["schema"] = value.split(".")[0]
                else:
                    result[key] = value
        return result

    # 将本地文件连接字符串转换成object
    def sourceToFileConfig(self, source):
        result = {
            "sourcetype": "file",
            "path": source
        }
        return result
