import requests

from kfrm_tool.include.setting.logger import KFRMLogger
from kfrm_tool.include.setting.name_list import BASE_GEOSERVER


class ReqGeoserver:
    def getGeoserverData(self, typeName, outputFormat, viewParams):
        data = {
            "service": "WFS",
            "version": "1.0.0",
            "request": "GetFeature",
            "typeName": "krm_geoserver:" + typeName,
            "viewparams": viewParams,
            "outputformat": outputFormat,
        }
        try:
            KFRMLogger.debug(f"Geoserver request data: {data}")
            req = requests.post(BASE_GEOSERVER, data=data, verify=False)
            req.raise_for_status()  # HTTP 오류 발생시 예외 발생

            KFRMLogger.debug(f"Geoserver response status: {req.status_code}")
            KFRMLogger.debug(
                f"Geoserver response content: {req.content[:200]}..."
            )  # 응답 내용의 처음 200자만 로깅

            return req

        except requests.exceptions.RequestException as e:
            KFRMLogger.error(f"Geoserver request failed: {str(e)}")
            if hasattr(e.response, "content"):
                KFRMLogger.error(f"Error response: {e.response.content}")
            raise Exception(f"Geoserver connection failed: {str(e)}")

        except Exception as e:
            KFRMLogger.error(f"Unexpected error in Geoserver request: {str(e)}")
            raise Exception(f"Geoserver error: {str(e)}")

    def getContentsToCSV(self, typeName, outputPath, viewParams=""):
        req = self.getGeoserverData(typeName, "csv", viewParams)
        text = req.text.split("\r\n")
        content = []
        for t in text:
            s = t.split(",", 1)
            if len(s) > 1:
                content.append(s[1].replace("  ", ""))

        with open(outputPath, "w", encoding="cp949") as f:
            f.write("\n".join(content))

    def getContentsToList(self, typeName, column, viewParams=""):
        req = self.getGeoserverData(typeName, "application/json", viewParams)
        features = req.json()["features"]

        if column:
            lst = [str(i["properties"][column]) for i in features]
        else:
            lst = features

        return lst

    def dataProcessing(self, features):
        lst = []
        for f in features:
            l = []
            prop = f["properties"]
            for p in prop:
                l.append(prop[p])
            lst.append(l)

        return lst
