#!/usr/bin/python3

# Copyright 2013-2016 University of Warsaw
# 
# 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.

__author__ = "Mateusz Kobos mkobos@icm.edu.pl"

import sys
import argparse
from vipe.oozie2png import convert_oozie_to_png
from vipe.graphviz.importance_score_map import DetailLevel

def parse():
    """Parse CLI arguments"""
    parser = argparse.ArgumentParser(
        description='Convert Oozie XML file to PNG image of data dependencies. '
            'The Oozie XML file has to be provided on stdin '
            'and the output image is produced on stdout.')
    detail_level_default = 'medium'
    detail_levels = [l.name for l in DetailLevel]
    detail_levels_str = ', '.join(['"{}"'.format(l) for l in detail_levels])
    parser.add_argument('--detail_level', default=detail_level_default, 
        metavar='NAME',
        help='How much detailed the graph should be. '
            'Possible values: {}. The default value: "{}"'.format(
                detail_levels_str, detail_level_default))
    parser.add_argument('--show_input_ports', action='store_true', 
        default=False)
    parser.add_argument('--show_output_ports', action='store_true', 
        default=False)
    parser.add_argument('--horizontal_orientation', action='store_true',
        default=False, help='If set, the graph will have horizontal '
                            'orientation')
    default_dot_program_path = '/usr/bin/dot'
    parser.add_argument('--dot_program', default=default_dot_program_path, 
        metavar='PATH',
        help='The path to the "dot" program from GraphViz library. '
            'The default value is "{}".'\
                .format(default_dot_program_path))
    args = parser.parse_args()
    if args.detail_level not in detail_levels:
        parsing_error('Entered detail_level option ("{}") is not one of the '
                      'acceptable values.'.format(args.detail_level))
    return args

def parsing_error(message):
    print('ERROR when parsing command-line arguments: {}'.format(message),
          file=sys.stderr)
    sys.exit(2)

args = parse()
xml_string = sys.stdin.read()
image = convert_oozie_to_png(xml_string, DetailLevel[args.detail_level], 
                             args.show_input_ports, args.show_output_ports, 
                             not args.horizontal_orientation)
sys.stdout.buffer.write(image)