#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
#*******************************************************************************
#
#  Copyright 2025 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-06-database-stat.py

This example shows how to open an existing database and output some
information about the database like the list of point attributes,
number of points and point cloud extents.
"""

import riegl.rdb

# Open existing database using default settings
with riegl.rdb.rdb_open("pointcloud.rdbx") as rdb:
    print("META DATA:")
    for key in rdb.meta_data:
        print(f"  Name:  {key}")
        print(f"  Value: {rdb.meta_data[key]}")
        print("-" * 80)
        # to write text: rdb.meta_data["my_text"] = "Example"
        # to write JSON: rdb.meta_data["my_json"] = json.dumps({"name": "value"})

    print("POINT ATTRIBUTES:")
    for attribute in rdb.point_attributes.values():
        print(f"  Name:         {attribute.name}")
        print(f"  Title:        {attribute.title}")
        print(f"  Description:  {attribute.description}")
        print(f"  Unit:         {attribute.unit_symbol}")
        print(f"  Length:       {attribute.length}")
        print(f"  Resolution:   {attribute.resolution}")
        print(f"  MinimumValue: {attribute.minimum_value}")
        print(f"  MaximumValue: {attribute.maximum_value}")
        print(f"  DefaultValue: {attribute.default_value}")
        print("-" * 80)

    with rdb.stat as stat:
        print("POINT CLOUD STATISTICS:")
        print(f"  Total point count: {stat.point_count_total}")
        print(f"  Minimum X, Y, Z:   {stat.minimum('riegl.xyz')}")
        print(f"  Maximum X, Y, Z:   {stat.maximum('riegl.xyz')}")

        print("PRIMARY INDEX STATISTICS:")
        leaves = [
            (
                leaf.point_count_node,
                leaf.minimum("riegl.xyz"),
                leaf.maximum("riegl.xyz")
            )
            for leaf in stat.leaves
        ]
        print(f"  Number of leaf nodes: {len(leaves)}")
        print("  Point count, minimum and maximum coordinates for all leaves:")
        for leaf in leaves:
            print(f"  {leaf[0]}, {leaf[1]} - {leaf[2]}")
