#!/usr/bin/env python
#
# This file is part of REPA: Release Engineering Process Assistant.
#
# Copyright (C) 2013 Intel Corporation
#
# REPA is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# version 2 as published by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
# MA 02110-1301, USA.

"""
REPA: Release Engineering Process Assistant.

Copyright (C) Intel Corporation 2013
Licence: GPL version 2
Author: Ed Bartosh <eduard.bartosh@intel.com>

List module.
Get list of submissions.
"""

import sys

from collections import defaultdict

from repa.common import get_project_by_name, get_download_url, get_obs_url
from repa.obs import OBS

from repa.main import sub_main

def get_status(results):
    """Gest submission status."""
    # Process project build results
    codes = set()
    for target in results.itervalues():
        codes.add(target.get('code'))
        codes.add(target.get('state'))
        for pkginfo in target['packages']:
            codes.add(pkginfo[1])
    status = ','.join(codes) or 'None'
    return status


def show(obs, name, target):
    """Print detailed info about submission or submitgroup."""
    is_group = name.startswith('submitgroup/')
    _, meta, build_results = get_project_by_name(obs, name, target)

    print
    if is_group:
        print 'Submit Group:', name
    else:
        print 'Submission:', name
    print 'Target project:', target
    if 'git_commit' in meta:
        print 'Commit:', meta['git_commit']
    if 'submitter' in meta:
        print 'Submitter:', meta['submitter']

    download_url = get_download_url(meta)
    if download_url:
        print 'Download Url:', download_url
    print 'OBS Url:', get_obs_url(meta)

    if is_group:
        print 'Submissions:'
        for subm in meta['submissions']:
            print '   ', subm
    else:
        print 'Git trees:'
        for tree in meta['projects']:
            print '   ', tree
    if 'images' in meta:
        print
        print 'Images:'
        for img in meta['images']:
            print '    %-40s %s' % (img['name'], img['status'])

    if build_results:
        result = defaultdict(list)
        for (repo, arch), target in build_results.iteritems():
            for pkg, status in target['packages']:
                if status not in ('succeeded', 'building',
                                  'blocked', 'disabled'):
                    result[(repo, arch)].append((pkg, status))
        if result:
            print
            print 'Package build failures:'
            for (repo, arch), pkginfo in result.iteritems():
                if pkginfo:
                    print '    %s/%s' % (repo, arch)
                    for pkg, status in pkginfo:
                        print '        %-40s %s' % (pkg, status)


class Show(object):
    """Subcommand: Print detailed information about submission."""

    name = 'show'
    description = 'Information about submission'
    help = description

    @staticmethod
    def add_arguments(parser, _):
        """
        Add arguments to the parser. Called from [sub_]main.
        Set defaults for arguments from config.
        """
        parser.add_argument('submission', help='submission or group')

    @staticmethod
    def run(argv):
        """Command line entry point. Called from [sub_]main"""
        obs = OBS(argv.apiurl, argv.apiuser, argv.apipasswd)
        return show(obs, argv.submission, argv.project)


if __name__ == '__main__':
    sys.exit(sub_main(sys.argv[1:], Show()))
