#! /usr/bin/env python3
#
# This file was auto-generated by shacl2code 1.0.0. DO NOT MANUALLY MODIFY IT
#
# SPDX-License-Identifier: MIT

import argparse
from pathlib import Path
from typing import Any, Iterable, List

from .model import (
    JSONLDDeserializer,
    JSONLDSerializer,
    ListProxy,
    SHACLObject,
    SHACLObjectSet,
)


def print_tree(objects: Iterable[SHACLObject], all_fields: bool = False) -> None:
    """
    Print object tree
    """
    seen = set()

    def callback(value: Any, path: List[str]) -> bool:
        s = ("  " * (len(path) - 1)) + f"{path[-1]}"
        if isinstance(value, SHACLObject):
            s += f" {value} ({id(value)})"
            is_empty = False
        elif isinstance(value, ListProxy):
            is_empty = len(value) == 0
            if is_empty:
                s += " []"
        else:
            s += f" {value!r}"
            is_empty = value is None

        if all_fields or not is_empty:
            print(s)

        if isinstance(value, SHACLObject):
            if value in seen:
                return False
            seen.add(value)
            return True

        return True

    for o in objects:
        o.walk(callback)


def main() -> int:
    parser = argparse.ArgumentParser(description="Python SHACL model test")
    parser.add_argument("infile", type=Path, help="Input file")
    parser.add_argument("--print", action="store_true", help="Print object tree")
    parser.add_argument("--outfile", type=Path, help="Output file")

    args = parser.parse_args()

    objectset = SHACLObjectSet()
    with args.infile.open("r") as f:
        d = JSONLDDeserializer()
        d.read(f, objectset)

    if args.print:
        print_tree(objectset.objects)

    if args.outfile:
        with args.outfile.open("wb") as f:
            s = JSONLDSerializer()
            s.write(objectset, f)

    return 0
