# -*- coding: utf-8 -*-
import os
import subprocess

from qgis import processing

from grm.lib.Util import GetQGIS_Path, MsError

# Driver,Files,Size,Coordinate
# PixelSize,CornerCoordinates,NoDataValue


def GetRaster_info(raster):
    try:
        global RasterDic
        path = GetQGIS_Path()
        result = (
            subprocess.check_output(
                '"' + path + '/bin/gdalinfo.exe"' + ' "' + raster + '"', shell=True
            ).decode("ascii")
        ).splitlines()
        CoordIndex = [i for i, s in enumerate(result) if "Origin" in s][0]
        CoordStr = " ".join([result[i] for i in range(5, CoordIndex)])
        CornerCoordinates = " ".join(
            [result[i] for i in range(CoordIndex + 7, CoordIndex + 12)]
        )
        RasterDic = {
            "Driver": result[0].replace("Driver:", "").strip(),
            "Files": result[1].replace("Files:", "").strip(),
            "Size": result[2].replace("Size is ", "").strip(),
            "Coordinate": CoordStr,
            "PixelSize": result[CoordIndex + 1]
            .replace("Pixel Size = (", "")
            .replace(")", "")
            .strip(),
            "CornerCoordinates": CornerCoordinates,
            "NoDataValue": result[-1].replace("NoData Value=", "").strip(),
        }
        return RasterDic
    except Exception as e:
        MsError(e)


def AscToShape(asc, shp):
    try:
        # 2022.01.10 동  : 같은 파일에 이 작업을 여러번 반복할수록 column 개수가 중복되어서 늘어남.
        if os.path.exists(shp):
            return True

        input = asc
        field = "DN"
        output = shp
        params = {"FIELD": field, "INPUT": input, "OUTPUT": output, "BAND": 1}
        processing.run("gdal:polygonize", params)
        return os.path.exists(output)
    except Exception as e:
        MsError(e)
