#!/usr/bin/env python3

# Copyright 2013-2015 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.oozie.reader.reader import read as oozie_read
from vipe.oozie.converter.converter import convert as oozie_convert
from vipe.pipeline.pipeline import Pipeline
from vipe.oozie.converter.iis import IISPipelineConverter
from vipe.graphviz.converter import Converter as PipelineConverter
from vipe.graphviz.image_converter import ImageConverter
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()
oozie_graph = oozie_read(xml_string)
pipeline = oozie_convert(oozie_graph, IISPipelineConverter())
dot_converter = PipelineConverter(DetailLevel[args.detail_level], 
        args.show_input_ports, args.show_output_ports, 
        not args.horizontal_orientation)
dot_string = dot_converter.run(pipeline)
dot_processor = ImageConverter(dot_string, dot_program_path=args.dot_program)
image = dot_processor.to_image()
sys.stdout.buffer.write(image)