# Path: lrs/lrs/utils.py
# def debug(msg):
#     print("LRSDEBUG: %s" % msg)
#     # sys.stdout.flush()  # gives error on Windows if Python console is not open
#     QgsMessageLog.logMessage(msg, 'LRS Plugin', Qgis.Info)
# 
# Path: lrs/lrs/error/lrslayermanager.py
# class LrsLayerManager(object):
#     def __init__(self, layer):
#         super(LrsLayerManager, self).__init__()
#         self.layer = layer
#         self.featureIds = {}  # dictionary of features with checksum keys
# 
#     # remove all features
#     def clear(self):
#         if not self.layer: return
#         fids = []
#         for feature in self.layer.getFeatures():
#             fids.append(feature.id())
# 
#         self.layer.dataProvider().deleteFeatures(fids)
# 
#         for fid in fids:
#             # hack to update attribute table
#             self.layer.featureDeleted.emit(fid)
# 
#     # transform features if necessary to layer crs
#     # modifies original feature geometry
#     def transformFeatures(self, features, crs):
#         if crs != self.layer.crs():
#             transform = QgsCoordinateTransform(crs, self.layer.crs(), QgsProject.instance())
#             for feature in features:
#                 # feature.geometry().transform(transform)  # does not work
#                 geo = feature.geometry()
#                 geo.transform(transform)
#                 feature.setGeometry(geo)
#         return features
# 
#         # add features with getChecksum() method
# 
#     def addFeatures(self, features, crs):
#         # debug('addFeatures layer.crs = {} features crs = {}'.format(self.layer.crs().authid(), crs.authid()))
#         features = self.transformFeatures(features, crs)
# 
#         status, addedFeatures = self.layer.dataProvider().addFeatures(features)
#         for feature, addedFeature in zip(features, addedFeatures):
#             self.featureIds[feature.getChecksum()] = addedFeature.id()
#             # hack to update attribute table
#             self.layer.featureAdded.emit(addedFeature.id())
# 
#     # delete features by checksums
#     def deleteChecksums(self, checksums):
#         fids = []
#         for checksum in checksums:
#             fid = self.featureIds.get(checksum, None)
#             if fid:
#                 fids.append(fid)
# 
#         if len(fids) > 0:
#             self.layer.dataProvider().deleteFeatures(fids)
# 
#         for fid in fids:
#             # hack to update attribute table
#             self.layer.featureDeleted.emit(fid)
# 
#     def updateFeatures(self, features, crs):
#         features = self.transformFeatures(features, crs)
#         changedGeometries = {}
#         changedAttributes = {}
#         for feature in features:
#             checksum = feature.getChecksum()
#             fid = self.featureIds.get(checksum, None)
#             if not fid: raise Exception("Error feature not found")
#             changedGeometries[fid] = feature.geometry()
#             changedAttributes[fid] = feature.getAttributeMap()
#         # debug ( "changedGeometries: %s" % changedGeometries )
#         self.layer.dataProvider().changeGeometryValues(changedGeometries)
#         self.layer.dataProvider().changeAttributeValues(changedAttributes)
# 
#         # hack to update attribute table
#         for fid, attr in changedAttributes.items():
#             for i, value in attr.items():
#                 self.layer.attributeValueChanged.emit(fid, i, value)
# 
# Path: lrs/lrs/error/lrserrorfeature.py
# class LrsErrorFeature(LrsFeature):
#     def __init__(self, error):
#         super(LrsErrorFeature, self).__init__(LRS_ERROR_FIELDS)
#         error = error
#         self.setGeometry(error.geo)
#         self.checksum = error.getChecksum()
# 
#         values = {
#             'error': error.typeLabel(),
#             'route': '%s' % error.routeId,
#             'measure': error.getMeasureString()
#         }
#         for name, value in values.items():
#             self.setAttribute(name, value)
# 
#     def __str__(self):
#         attributes = []
#         for i in range(len(self.fields())):
#             name = self.fields()[i].name()
#             attributes.append( "%s:%s" % ( name, self.attribute(name) ) )
#         s = "errorFeature: " + " ".join(attributes)
#         if self.geometry():
#             s += " " + self.geometry().exportToWkt()
#         return s
# 
#     def getChecksum(self):
#         return self.checksum


from qgis.core import QgsWkbTypes
from ..utils import debug
from .lrslayermanager import LrsLayerManager
from .lrserrorfeature import LrsErrorFeature
    def addErrors(self, errors, crs):
        if self.layer is None:
            return
        #debug("addErrors geometryType = %s errors count = %s" % (self.layer.geometryType(), len(errors)))

        features = []
        for error in errors:
            #debug("addErrors %s" % error)
            if not self.errorTypeMatch(error):
                continue
            feature = LrsErrorFeature(error)
            #debug("addErrors %s" % feature)
            features.append(feature)

        self.addFeatures(features, crs)

    def updateErrors(self, errorUpdates):
        # debug ( "%s" % errorUpdates )
        if self.layer is None:
            return

        # delete
        self.deleteChecksums(errorUpdates['removedErrorChecksums'])

        # update
        features = []
        for error in errorUpdates['updatedErrors']:
            if not self.errorTypeMatch(error):
                continue


# Path: lrs/lrs/utils.py
# def debug(msg):
#     print("LRSDEBUG: %s" % msg)
#     # sys.stdout.flush()  # gives error on Windows if Python console is not open
#     QgsMessageLog.logMessage(msg, 'LRS Plugin', Qgis.Info)
# 
# Path: lrs/lrs/error/lrslayermanager.py
# class LrsLayerManager(object):
#     def __init__(self, layer):
#         super(LrsLayerManager, self).__init__()
#         self.layer = layer
#         self.featureIds = {}  # dictionary of features with checksum keys
# 
#     # remove all features
#     def clear(self):
#         if not self.layer: return
#         fids = []
#         for feature in self.layer.getFeatures():
#             fids.append(feature.id())
# 
#         self.layer.dataProvider().deleteFeatures(fids)
# 
#         for fid in fids:
#             # hack to update attribute table
#             self.layer.featureDeleted.emit(fid)
# 
#     # transform features if necessary to layer crs
#     # modifies original feature geometry
#     def transformFeatures(self, features, crs):
#         if crs != self.layer.crs():
#             transform = QgsCoordinateTransform(crs, self.layer.crs(), QgsProject.instance())
#             for feature in features:
#                 # feature.geometry().transform(transform)  # does not work
#                 geo = feature.geometry()
#                 geo.transform(transform)
#                 feature.setGeometry(geo)
#         return features
# 
#         # add features with getChecksum() method
# 
#     def addFeatures(self, features, crs):
#         # debug('addFeatures layer.crs = {} features crs = {}'.format(self.layer.crs().authid(), crs.authid()))
#         features = self.transformFeatures(features, crs)
# 
#         status, addedFeatures = self.layer.dataProvider().addFeatures(features)
#         for feature, addedFeature in zip(features, addedFeatures):
#             self.featureIds[feature.getChecksum()] = addedFeature.id()
#             # hack to update attribute table
#             self.layer.featureAdded.emit(addedFeature.id())
# 
#     # delete features by checksums
#     def deleteChecksums(self, checksums):
#         fids = []
#         for checksum in checksums:
#             fid = self.featureIds.get(checksum, None)
#             if fid:
#                 fids.append(fid)
# 
#         if len(fids) > 0:
#             self.layer.dataProvider().deleteFeatures(fids)
# 
#         for fid in fids:
#             # hack to update attribute table
#             self.layer.featureDeleted.emit(fid)
# 
#     def updateFeatures(self, features, crs):
#         features = self.transformFeatures(features, crs)
#         changedGeometries = {}
#         changedAttributes = {}
#         for feature in features:
#             checksum = feature.getChecksum()
#             fid = self.featureIds.get(checksum, None)
#             if not fid: raise Exception("Error feature not found")
#             changedGeometries[fid] = feature.geometry()
#             changedAttributes[fid] = feature.getAttributeMap()
#         # debug ( "changedGeometries: %s" % changedGeometries )
#         self.layer.dataProvider().changeGeometryValues(changedGeometries)
#         self.layer.dataProvider().changeAttributeValues(changedAttributes)
# 
#         # hack to update attribute table
#         for fid, attr in changedAttributes.items():
#             for i, value in attr.items():
#                 self.layer.attributeValueChanged.emit(fid, i, value)
# 
# Path: lrs/lrs/error/lrserrorfeature.py
# class LrsErrorFeature(LrsFeature):
#     def __init__(self, error):
#         super(LrsErrorFeature, self).__init__(LRS_ERROR_FIELDS)
#         error = error
#         self.setGeometry(error.geo)
#         self.checksum = error.getChecksum()
# 
#         values = {
#             'error': error.typeLabel(),
#             'route': '%s' % error.routeId,
#             'measure': error.getMeasureString()
#         }
#         for name, value in values.items():
#             self.setAttribute(name, value)
# 
#     def __str__(self):
#         attributes = []
#         for i in range(len(self.fields())):
#             name = self.fields()[i].name()
#             attributes.append( "%s:%s" % ( name, self.attribute(name) ) )
#         s = "errorFeature: " + " ".join(attributes)
#         if self.geometry():
#             s += " " + self.geometry().exportToWkt()
#         return s
# 
#     def getChecksum(self):
#         return self.checksum


# Path: lrs/lrs/error/lrserrorlayermanager.py
from qgis.core import QgsWkbTypes
from ..utils import debug
from .lrslayermanager import LrsLayerManager
from .lrserrorfeature import LrsErrorFeature

    def addErrors(self, errors, crs):
        if self.layer is None:
            return
        #debug("addErrors geometryType = %s errors count = %s" % (self.layer.geometryType(), len(errors)))

        features = []
        for error in errors:
            #debug("addErrors %s" % error)
            if not self.errorTypeMatch(error):
                continue
            feature = LrsErrorFeature(error)
            #debug("addErrors %s" % feature)
            features.append(feature)

        self.addFeatures(features, crs)

    def updateErrors(self, errorUpdates):
        # debug ( "%s" % errorUpdates )
        if self.layer is None:
            return

        # delete
        self.deleteChecksums(errorUpdates['removedErrorChecksums'])

        # update
        features = []
        for error in errorUpdates['updatedErrors']:
            if not self.errorTypeMatch(error):
                continue


            feature = LrsErrorFeature(error)