#!/usr/bin/env python3

import click

CONTEXT_SETTINGS = dict(help_option_names=['-h', '--help', '-?'])
from click_default_group import DefaultGroup

#
# 'cli' group (root group)
#

# This is our entrypoint - the main "show" command
@click.group(
	default='poll',
	cls=DefaultGroup,
	default_if_no_args=True,
	context_settings=CONTEXT_SETTINGS
)
@click.pass_context
def cli(ctx):
    """NVIDIA Cumulus Linux - what-just-happened command line"""



''' what-just-happened command line interface '''

import sys
import subprocess
import click
#from swsssdk import ConfigDBConnector
from tabulate import tabulate
from natsort import natsorted


WHAT_JUST_HAPPENED_SERVICE_NAME = 'what-just-happened'


def is_wjh_enabled():
	''' Return true if the state of what-just-happened in FEATURE table is "enabled" '''
	return subprocess.call(["systemctl", "status", "what-just-happened.service"], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) == 0

@cli.command()
def dump():
    ''' Dump what-just-happened debug information '''
    if not is_wjh_enabled():
        click.echo(
            '"{}" feature is disabled, run "systemctl start {}"'
                .format(WHAT_JUST_HAPPENED_SERVICE_NAME, WHAT_JUST_HAPPENED_SERVICE_NAME),
            err=True)
        return
    cmd = 'docker exec -i {} /usr/bin/wjhcli -d'.format(WHAT_JUST_HAPPENED_SERVICE_NAME)
    proc = subprocess.Popen(['/bin/bash', '-c', cmd],
                            stdout=sys.stdout, stderr=sys.stderr)
    proc.wait()


@cli.command()
@click.argument('channels', nargs=-1)
@click.option('--aggregate', is_flag=True, help='Dump aggregated counters')
@click.option('--export', is_flag=True, help='Save droped packets into pcap file')
@click.option('--no_metadata', is_flag=True, help='Save the pcap file without metadata')
def poll(channels, aggregate, export, no_metadata):
    ''' Poll what-just-happened user channel '''

    if no_metadata and not export:
        click.echo("no_metadata option is avilable only with export. \nAborting!", err=True)
        return

    #config_db = ConfigDBConnector()
    #config_db.connect()
    #wjh_channel_table = config_db.get_table('WJH_CHANNEL')
    configured_channels = ["forwarding"]

    if not is_wjh_enabled():
        click.echo(
            '"{}" feature is disabled, run "systemctl start {}"'
                .format(WHAT_JUST_HAPPENED_SERVICE_NAME, WHAT_JUST_HAPPENED_SERVICE_NAME),
            err=True)
        return

    if not channels:
        channels = natsorted(configured_channels)
        if not channels:
            click.echo("No what-just-happened channels configured")
            return
    else:
        for channel in channels:
            if channel not in configured_channels:
                click.echo("What-just-happened channel {} does not exits".format(channel),
                           err=True)
                return

    cmd = 'docker exec -i {} /usr/bin/wjhcli {} {} {} {}'.format(
        WHAT_JUST_HAPPENED_SERVICE_NAME,
        ' '.join(['-c {}'.format(chan) for chan in channels]),
        '-p' if export else '',
        '-a' if aggregate else '',
        '-m' if no_metadata else '')
    proc = subprocess.Popen(['/bin/bash', '-c', cmd],
                            stdout=sys.stdout, stderr=sys.stderr)
    proc.wait()


if __name__ == '__main__':
    cli()
