#!/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. Generate all the tables"
               " in the config file, where each section corresponds to a"
               " table, and output them as a single HTML page.")


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.")
    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'])

        print '<html>'
        for section in config.sections():
            params = dict(config.items(section))
            table_type = params.get('table-type')
            table = launchpadstats.get_table(table_type, params)
            table.generate()
            header = params.get('description', section)
            print '<h2>%s</h2>' % header
            print table.html()
        print '</html>'

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


main()
