#!/usr/bin/env python

import argparse

from ros_introspection.package_xml import DEPEND_ORDERING
from ros_introspection.util import get_packages

parser = argparse.ArgumentParser()
parser.add_argument('-m', '--multiple_distros', action='store_true',
                    help='Use this option when a single branch will be used for both Python2 and Python3')
args = parser.parse_args()

pkgs = get_packages()

# TODO(dlu): Replace Orocos KDL and BFL rosdep keys
# TODO(dlu): package_dir option for weird Python location


for package in pkgs:
    # Upgrade CMake Version
    package.cmake.upgrade_minimum_version((3, 0, 2))

    # Setuptools instead of Distutils
    if package.setup_py and not package.setup_py.noetic:
        package.setup_py.noetic = True
        package.setup_py.changed = True

    manifest = package.manifest

    # Set up python*_setuptools buildtool_depend
    if package.setup_py and args.multiple_distros:
        if 'python-setuptools' not in manifest.get_packages_by_tag('buildtool_depend'):
            new_tag = manifest.tree.createElement('buildtool_depend')
            new_tag.appendChild(manifest.tree.createTextNode('python-setuptools'))
            manifest.insert_new_tag(new_tag)
            manifest.changed = True

    # Python 3 Dependencies
    for tag_name in DEPEND_ORDERING:
        existing = manifest.get_packages_by_tag(tag_name)
        for el in manifest.root.getElementsByTagName(tag_name):
            dependency = el.childNodes[0].nodeValue
            if not dependency.startswith('python'):
                continue
            py3 = dependency.startswith('python3-')
            if not py3:
                py3_version = dependency.replace('python-', 'python3-')
                if args.multiple_distros:
                    el.setAttribute('condition', '$ROS_PYTHON_VERSION == 2')
                    if py3_version not in existing:
                        new_tag = manifest.tree.createElement(tag_name)
                        new_tag.setAttribute('condition', '$ROS_PYTHON_VERSION == 3')
                        new_tag.appendChild(manifest.tree.createTextNode(py3_version))
                        manifest.insert_new_tag(new_tag)
                else:
                    el.childNodes[0].nodeValue = py3_version
                manifest.changed = True

    # Upgrade to package.xml format 3
    if manifest.format < 3 and manifest.changed:
        manifest.upgrade(3)
    package.write()
