#!/usr/bin/env pmpython
#
# Copyright (C) 2015-2017 Red Hat.
#
# This program is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by the
# Iostat Software Foundation; either version 2 of the License, or (at your
# option) any later version.
#
# 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.
#
# pylint: disable=C0103,R0914,R0902
""" Display running process IDs and names """

import sys
from pcp import pmapi, pmcc
from cpmapi import (PM_CONTEXT_ARCHIVE, PM_MODE_FORW)

METRICS = ['']

class ProcReport(pmcc.MetricGroupPrinter):

    def __init__(self):
        """ Construct object - prepare for command line handling """
        pmcc.MetricGroupPrinter.__init__(self)

    def pid_dict(self, group, metric):
        """ Create an instance:value dictionary for the given metric """
        values = group[metric].netConvValues
        if not values:
            return {}
        return dict(map(lambda x: (x[1], x[2]), values))

    def report(self, groups):
        self.convert(groups)
        group = groups['proc']
        pids = self.pid_dict(group, METRICS[0])
        pidlist = pids.keys()
        for pidinst in sorted(pidlist):
            print("%s" % pidinst)
        sys.exit(0)

if __name__ == '__main__':
    try:
        options = pmapi.pmOptions('a:h:?')
        options.pmSetShortUsage("[options] metric")
        options.pmSetLongOptionArchive()
        options.pmSetLongOptionHost()
        options.pmSetLongOptionHelp()
        manager = pmcc.MetricGroupManager.builder(options, sys.argv)
        if manager.type == PM_CONTEXT_ARCHIVE:
            origin = options.pmGetOptionOrigin()
            manager.pmSetMode(PM_MODE_FORW, origin, 0)
        manager.printer = ProcReport()
        METRICS = options.pmGetOperands()
        if METRICS == None:
            raise pmapi.pmUsageErr()
        manager['proc'] = METRICS
        manager.run()
    except pmapi.pmErr as error:
        print('%s: %s\n' % (error.progname(), error.message()))
    except pmapi.pmUsageErr as usage:
        usage.message()
        sys.exit(1)
    except KeyboardInterrupt:
        pass
