
from qgis.core import (QgsVectorLayer, QgsField, QgsCoordinateReferenceSystem, QgsVectorFileWriter, QgsProject,
                       QgsSymbol, QgsRendererCategory, QgsCategorizedSymbolRenderer, QgsRendererCategory, 
                       QgsSimpleFillSymbolLayer)


def generate_layer(typ_geometrie, nazev, fields:dict, typ="memory"):

    layer = QgsVectorLayer(typ_geometrie, nazev, typ)
    layer_provider = layer.dataProvider()
    layer_fields = [QgsField(name, field_type) for name, field_type in fields.items()]
    layer_provider.addAttributes(layer_fields)
    layer.updateFields()

    return layer

def ulozeni_vektorove_vrstvy(lyr, EPSG, path_lyr, DN="ESRI Shapefile", FE="windows-1250"):
    options = QgsVectorFileWriter.SaveVectorOptions()
    options.driverName = DN
    options.fileEncoding = FE
    options.destCRS = QgsCoordinateReferenceSystem("EPSG:" + EPSG)
    error = QgsVectorFileWriter.writeAsVectorFormatV3(lyr, path_lyr, QgsProject.instance().transformContext(), options)
    if error[0] == QgsVectorFileWriter.WriterError.NoError:
        print(f"Exporotvana vrstva: {lyr}")
    else:
        print(error)

def symbology_kategorie(lyr, field, unique_values, colors_cat, names_cat):
    categories = []
    for unique_value in unique_values:
        symbol = QgsSymbol.defaultSymbol(lyr.geometryType())
        layer_style = {}
        layer_style['color'] = colors_cat[unique_values.index(unique_value)]
        layer_style['outline'] = '#000000'
        symbol_layer = QgsSimpleFillSymbolLayer.create(layer_style)
        if symbol_layer is not None:
            symbol.changeSymbolLayer(0, symbol_layer)
        category = QgsRendererCategory(unique_value, symbol,
                                        names_cat[unique_values.index(unique_value)])
        categories.append(category)
    renderer = QgsCategorizedSymbolRenderer(field, categories)
    if renderer is not None:
        lyr.setRenderer(renderer)
    lyr.triggerRepaint()


def mazani_poli(vrstva, list_pole, zustavaji=True):
    """
    Mazání polí ve vrstvě.

    Parameters
    ----------
    vrstva : QgsVectorLayer
    list_pole : list[str]
        Pokud zustavaji=True -> seznam polí, která mají zůstat.
        Pokud zustavaji=False -> seznam polí, která se mají smazat.
    zustavaji : bool
    """

    field_names = vrstva.fields().names()

    if zustavaji:
        pole_ke_smazani = [name for name in field_names if name not in list_pole]
    else:
        pole_ke_smazani = [name for name in field_names if name in list_pole]

    field_indexes = [vrstva.fields().indexFromName(name) for name in pole_ke_smazani]
    field_indexes = [idx for idx in field_indexes if idx >= 0]

    if not field_indexes:
        return

    vrstva.startEditing()
    vrstva.dataProvider().deleteAttributes(field_indexes)
    vrstva.updateFields()
    vrstva.commitChanges()
