#!/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.oozie.reader.reader import read
import vipe.oozie.converter.converter
from vipe.pipeline.pipeline import Pipeline
from vipe.oozie.converter.iis import IISPipelineConverter
import vipe.graphviz.converter
from vipe.graphviz.importance_score_map import DetailLevel


def parse():
    """Parse CLI arguments"""
    parser = argparse.ArgumentParser(
        description='Convert Pipeline YAML file to GraphViz dot representation. '
            'The Pipeline YAML file has to be provided on stdin '
            'and the output in dot format 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')
    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()
pipeline_yaml = sys.stdin.read()
pipeline = Pipeline.from_yaml_dump(pipeline_yaml)
dot_converter = vipe.graphviz.converter.Converter(
        DetailLevel[args.detail_level], 
        args.show_input_ports, args.show_output_ports,
        not args.horizontal_orientation)
dot_string = dot_converter.run(pipeline)
print(dot_string)