#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
#*******************************************************************************
#
#  Copyright 2026 RIEGL Laser Measurement Systems
#
#  Licensed under the Apache License, Version 2.0 (the "License");
#  you may not use this file except in compliance with the License.
#  You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
#  Unless required by applicable law or agreed to in writing, software
#  distributed under the License is distributed on an "AS IS" BASIS,
#  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#  See the License for the specific language governing permissions and
#  limitations under the License.
#
#  SPDX-License-Identifier: Apache-2.0
#
#*******************************************************************************
#
"""
rdb-example-04-update-points.py

This example shows how to open an existing database and modify some points.
This example is based on the database of rdb-example-1-create-database.
"""

import riegl.rdb

# Access existing database
with riegl.rdb.rdb_open("pointcloud.rdbx") as rdb:

    # Before we can modify the database, we must start a transaction
    with riegl.rdb.Transaction(
        rdb,  # point cloud object
        "Update",  # transaction title
        "Point Classifier v1.0"  # software name
    ) as transaction:

        # Prepare point attribute buffers
        buffer_size = 10000  # point block/chunk size
        buffer_point_number = riegl.rdb.AttributeBuffer(
            rdb.point_attributes["riegl.id"], buffer_size
        )
        buffer_point_class = riegl.rdb.AttributeBuffer(
            rdb.point_attributes["riegl.class"], buffer_size
        )

        # Start new select query to get point id of points with reflectance
        # below -20 dB
        with rdb.select("riegl.reflectance < -20.0") as select:
            select.bind(buffer_point_number)

            # Start new update query and define buffers
            with rdb.update() as update:
                update.bind(buffer_point_number)
                update.bind(buffer_point_class)

                # Process all points block-wise
                point_count = 1  # actual number of points not yet known
                while point_count > 0:
                    point_count = select.next(buffer_size)

                    #  Define new point class
                    for i in range(point_count):
                        buffer_point_class[i] = 7

                    # Actually update points
                    update.next(point_count)

        # Finally commit transaction
        transaction.commit()
