#!/usr/bin/env python3

# Copyright 2018 Open Source Robotics Foundation, Inc.
#
# 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.

import argparse
import pathlib
import sys

from lark.tree import pydot__tree_to_png

from rosidl_parser.parser import get_ast_from_idl_string


def main(argv=sys.argv[1:]):
    parser = argparse.ArgumentParser(
        description='Generate a .png file with the AST of an .idl file.',
        formatter_class=argparse.ArgumentDefaultsHelpFormatter)
    parser.add_argument(
        'idl_files', nargs='+',
        help='The path of the .idl files')
    args = parser.parse_args(argv)

    for idl_file in args.idl_files:
        print('idl_file', idl_file)
        idl_file = pathlib.Path(idl_file)
        if not idl_file.exists():
            print(f"File '{idl_file} not found", file=sys.stderr)
            continue

        string = idl_file.read_text()
        try:
            tree = get_ast_from_idl_string(string)
        except Exception as e:  # noqa: F841
            print(f"Failed to parse '{idl_file}': {e}", file=sys.stderr)
            continue

        png_file = idl_file.with_suffix('.png')
        try:
            pydot__tree_to_png(tree, png_file)
        except ImportError as e:  # noqa: F841
            print(f'Failed to generate png files: {e}', file=sys.stderr)
            return 1
        print(f"Generated '{png_file}'")


if __name__ == '__main__':
    sys.exit(main())
