# -*- coding: utf-8 -*-
import os
import subprocess
from .Util import *
import processing

#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:
        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)