
try:
    import gdal
    import osr
except:
    try:
        from osgeo import gdal, osr
    except:
        QMessageBox.information(None, "MagicWand", "Impossibile caricare librerie gdal e osr")


class RasterCreator(object):
    def __init__(self):
        pass


    def changeRasterValues(self, band):

        fmttypes = {'Byte': 'B', 'UInt16': 'H', 'Int16': 'h', 'UInt32': 'I', 'Int32': 'i', 'Float32': 'f',
                    'Float64': 'd'}

        data_type = band.DataType

        BandType = gdal.GetDataTypeName(band.DataType)

        raster = []

        for y in range(band.YSize):
            scanline = band.ReadRaster(0, y, band.XSize, 1, band.XSize, 1, data_type)
            values = struct.unpack(fmttypes[BandType] * band.XSize, scanline)
            raster.append(values)

        raster = [list(item) for item in raster]

        # changing raster values
        #for i, item in enumerate(raster):
        #    for j, value in enumerate(item):
        #        #if value > 98:
        #        #    #print i, j
        #        #    raster[i][j] = 0

        # transforming list in array
        raster = numpy.asarray(raster)

        return raster

    def creaLayer(self):
        layer = self.iface.activeLayer()

        provider = layer.dataProvider()

        path = provider.dataSourceUri()

        (raiz, filename) = os.path.split(path)

        dataset = gdal.Open(path)

        # Get projection
        prj = dataset.GetProjection()

        # setting band
        number_band = 1

        band = dataset.GetRasterBand(number_band)

        # Get raster metadata
        geotransform = dataset.GetGeoTransform()

        # Set name of output raster
        output_file = "C:\\Users\\caligola\\Desktop\\s\\raster_output.tif"

        # Create gtif file with rows and columns from parent raster
        driver = gdal.GetDriverByName("GTiff")

        raster = self.changeRasterValues(band)

        dst_ds = driver.Create(output_file,
                               band.XSize,
                               band.YSize,
                               number_band,
                               band.DataType)

        # writting output raster
        dst_ds.GetRasterBand(number_band).WriteArray(raster)

        # setting extension of output raster
        # top left x, w-e pixel resolution, rotation, top left y, rotation, n-s pixel resolution
        dst_ds.SetGeoTransform(geotransform)

        # setting spatial reference of output raster
        srs = osr.SpatialReference(wkt=prj)
        dst_ds.SetProjection(srs.ExportToWkt())
