#!/usr/bin/env python
# Copyright (c) 2014 Red Hat, 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 logging
import argparse
import sys
import traceback

import launchpadstats


logging.basicConfig()
LOG = logging.getLogger('launchpadstats')

DESCRIPTION = "Get Launchpad statistics trough Stackalytics and create" \
              " various types of tables out of them."


def parse_args():
    parser = argparse.ArgumentParser(description=DESCRIPTION)
    parser.add_argument('-v', '--verbose', action='store_true',
                        help="Show logging output.")
    parser.add_argument('-c', '--config', required=True,
                        help="Configuration file, by default use 'config.ini'"
                        " in the project directory.")
    parser.add_argument('-t', '--table-name', default='DEFAULT',
                        help="Which section name in the config file to use,"
                        " the default value is 'DEFAULT'.")
    parser.add_argument('--output-format', default='csv',
                        choices=['csv', 'html'],
                        help="What output format to use. Default is 'csv'.")
    args = vars(parser.parse_args())
    return args


def main():
    args = parse_args()
    if args['verbose']:
        LOG.setLevel(logging.INFO)
    try:
        config = launchpadstats.get_config(args['config'])
        params = dict(config.items(args['table_name']))
        table_type = params.get('table-type')

        table = launchpadstats.get_table(table_type, params)
        table.generate()
        if args['output_format'] == 'html':
            print table.html()
        else:
            print table.csv()

    except Exception, e:
        print "%s: %s" % (type(e).__name__, e)
        if args['verbose']:
            traceback.print_exc()
        sys.exit(1)


main()
