#! /usr/libexec/platform-python -s
#
# Copyright (c) 2023 - Adjacent Link LLC, Bridgewater, New Jersey
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# * Redistributions of source code must retain the above copyright
#   notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
#   notice, this list of conditions and the following disclaimer in
#   the documentation and/or other materials provided with the
#   distribution.
# * Neither the name of Adjacent Link LLC nor the names of its
#   contributors may be used to endorse or promote products derived
#   from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.

from argparse import ArgumentParser
from argparse import RawDescriptionHelpFormatter
import pandas as pd
import numpy as np
import sys
import time
import re
import signal
import os
import textwrap

from collections import defaultdict
from otestpoint.labtools import Stream
from otestpoint.interface.measurementtable_pb2 import MeasurementTable

from pyparsing import Keyword
from pyparsing import Suppress
from pyparsing import Literal
from pyparsing import Or
from pyparsing import delimitedList
from pyparsing import Group
from pyparsing import pyparsing_common
from pyparsing import Optional
from pyparsing import QuotedString

def expand_range(toks):
    start = min(toks[0][0],toks[0][1])
    end = max(toks[0][0],toks[0][1])
    return list(range(start,end + 1))

column_set = \
    delimitedList(Group(pyparsing_common.integer.copy() + \
                        Suppress(Literal('-')) + \
                        pyparsing_common.integer.copy()).setParseAction(expand_range) | \
                  pyparsing_common.integer.copy()).setParseAction(lambda toks : set(toks))

columns = Suppress(Or((Keyword('cols'),Keyword('c')))) + \
          Suppress(Literal('=')) + \
          Suppress(Literal('(')) + \
          column_set('cols') + \
          Suppress(Literal(')'))

optional_name = \
    Optional(Suppress(Literal('=>')) + \
             QuotedString(quoteChar="|")('col-name'))

pass_command = \
    Suppress(Keyword('pass')) +  \
    Suppress(Literal('(')) + \
    columns + \
    Suppress(Literal(')')) + \
    optional_name

pass_command = \
    pass_command.setResultsName('pass')

delta_command = \
    Suppress(Or((Keyword('delta'),Keyword('d')))) +  \
    Suppress(Literal('(')) + \
    columns + \
    Suppress(Literal(')')) + \
    optional_name

delta_command = \
    delta_command.setResultsName('delta')

interval_average_command = \
    Suppress(Or((Keyword('interval-average'),Keyword('iavg')))) +  \
    Suppress(Literal('(')) + \
    columns + \
    Suppress(Literal(',')) + \
    Suppress(Or((Keyword('sample-cols'),Keyword('n')))) + \
    Suppress(Literal('=')) + \
    Suppress(Literal('(')) + \
    column_set('sample-cols') + \
    Suppress(Literal(')')) + \
    Suppress(Literal(')')) + \
    optional_name

interval_average_command = \
    interval_average_command.setResultsName('interval-average')

pivot_command = \
    Suppress(Or((Keyword('values'),Keyword('v')))) + \
    Suppress(Literal('=')) + \
    Suppress(Literal('(')) + \
    column_set('values') + \
    Suppress(Literal(')')) + \
    Suppress(Literal(',')) + \
    Suppress(Or((Keyword('index'),Keyword('i')))) + \
    Suppress(Literal('=')) + \
    Suppress(Literal('(')) + \
    column_set('index') + \
    Suppress(Literal(')')) + \
    Suppress(Literal(',')) + \
    Suppress(Or((Keyword('cols'),Keyword('c')))) + \
    Suppress(Literal('=')) + \
    Suppress(Literal('(')) + \
    column_set('cols') + \
    Suppress(Literal(')'))

pivot_command = \
    pivot_command.setResultsName('pivot')

command_parser = \
    Or([pass_command,
        delta_command,
        interval_average_command,])

column_actions_description = \
    """\
    Column Actions
    ==============

    * Pass: Pass-through one or more columns without change.

    pass(cols=(...)); | pass(cols=(...))=>|label|;

    - cols=(...): Comma separated list of column integer indexes or
    range in the form M - N.

    - label: Column label string used to rename a column. If the first
    character of label is '=', label will replace the original column
    label. If label contains {}, the original column label will be
    substituted in its place prior to replacing the original column
    label.

    * Delta: Convert one ore more columns to the delta between the
    previous and current value.

    delta(cols=(...)); | d(cols=(...))=>|label|;

    - cols=(...): Comma separated list of column integer indexes or
    range in the form M - N.

    - label: Column label string used to rename a column. If the first
    character of label is '=', label will replace the original column
    label. If label contains {}, the original column label will be
    substituted in its place prior to replacing the original column
    label.

    * Interval Average: Convert one ore mote long running average
      columns to an interval average.

    interval-average(cols=(...),n=(...)); | iavg(cols=(...),n=(...))=>|label|;

    - cols=(...): Comma separated list of long running average column
    integer indexes or range in the form M - N.

    - n(...) | sample-cols(...): Comma separated list of long running
    average sample size column integer indexes or range in the form M
    - N. More than one column will be summed to use the total as the
    sample size when computing the interval average.

    - label: Column label string used to rename a column. If the first
    character of label is '=', label will replace the original column
    label. If label contains {}, the original column label will be
    substituted in its place prior to replacing the original column
    label.

    Example:

    Pass-through the rfsignaltable published by node-1's and node-3's
    respective EMANE.RFPipe.Tables.Receive probe.

    $ otestpoint-labtools-mtabletool \\
       localhost:9002 \\
       Measurement_emane_rfpipe_tables_receive@rfsignaltable \\
       EMANE.RFPipe.Tables.Receive.node-1 EMANE.RFPipe.Tables.Receive.node-3

    Convert the rfsignaltable of all node EMANE.RFPipe.Tables.Receive
    probes. Pass columns [0,2] as is, convert column 3 to an interval
    delta and append '_int' to the column label, convert columns [4,7]
    to an interval average using column 3 as the number of samples and
    append '_int' to the column labels.

    $ otestpoint-labtools-mtabletool \\
       localhost:9002 \\
       Measurement_emane_rfpipe_tables_receive@rfsignaltable \\
       EMANE.RFPipe.Tables.Receive \\
       --actions \\
        "pass(c=(0-2));" \\
        "delta(c=(3))=>|{}_int|;" \\
        "iavg(c=(4,5,6,7),n=(3))=>|{}_int|;"


    Pivot Table
    ===========

    Pivot the table that results from Column Actions before
    displaying.

    * values=(..): Comma separated list of column integer indexes or
    range in the form M - N. Columns to use for populating new table’s
    values.

    * index=(...): Comma separated list of column integer indexes or
    range in the form M - N. Columns to use to make new table’s index.

    * cols=(...): Comma separated list of column integer indexes or
    range in the form M - N. Columns to use to make new table’s
    columns.

    Example:

    Build a combinded eventreceptiontable publishes by all nodes'
    EMANE.PhysicalLayer.Tables.Events probe.

    $ otestpoint-labtools-mtabletool \\
       localhost:9002 \\
       Measurement_emane_physicallayer_tables_events@eventreceptiontable \\
       EMANE.PhysicalLayer.Tables.Events \\
       --actions \\
       "pass(c=(0));" \\
       "pass(c=(1))=>|Total|};" \\
       --pivot \\
       "values=(2),index=(0),cols=(1);"

    Convert the eventreceptiontable of all node
    EMANE.PhysicalLayer.Tables.Events probes. Pass column 0 as is,
    pass column 1 as is but change the column name to 'Total'. Pivot
    the resulting table using column 0 (node name), as the index,
    column 1 (event id) as the new column names, and column 2 (event
    counts) as the new column values.
    """


argument_parser = ArgumentParser(description="A tool for manipulating an OpenTestPoint"
                                 " MeasurementTable for display purposes.",
                                 formatter_class=RawDescriptionHelpFormatter,
                                 epilog=column_actions_description)

argument_parser.add_argument('endpoint',
                             type=str,
                             help="OpenTestPoint publish endpoint.")

argument_parser.add_argument('measurement-table',
                             type=str,
                             help="measurment table in the form MEASURMENT@TABLE_NAME.")

argument_parser.add_argument('probe',
                             type=str,
                             nargs='+',
                             help="probe")

argument_parser.add_argument('--actions',
                             type=str,
                             nargs='+',
                             help="individual column actions. See 'Column Actions'."
                             " When none specified, the entire table is passed through.")

argument_parser.add_argument('--pivot',
                             type=str,
                             help="pivot table. See 'Pivot Table'.")

argument_parser.add_argument('--column-keys',
                             type=int,
                             nargs='*',
                             default=[0],
                             metavar='COLUMN',
                             help="column keys for actions that require previous value"
                             " comparisons: delta and iavg. [default: %(default)s]")

ns = argument_parser.parse_args()

args = vars(ns)

measurments = defaultdict(list)
probes = []

m = re.match(r'^(.+)@([^,]+(?:,[^,]+)*)$',args['measurement-table'])

if m:
    measurments[m.group(1)].extend(m.group(2).split(','))
else:
    print('error: malformed measurment-table: {}'.format(args['measurement-table']))

probes = args['probe']

if args['actions']:
    column_command_string = ' '.join(args['actions'])
else:
    column_command_string = ''

commands = column_command_string.split(';')
actions = defaultdict(list)

for c in commands:
    if c:
        elements = command_parser.parseString(c.strip())
        name = elements.getName()
        params = elements.asDict()

        if name == 'key':
            pass
        else:
            if (name == 'delta' or name =='interval-average'):
                if 'column_keys' not in args:
                    print('error: must specify column keys for actions that require previous value comparisons'.format(col))
                    exit(1)

        for col in params['cols']:
            actions[col].append((name,params))

pivot_params = {}

if args['pivot']:
    elements = pivot_command.parseString(args['pivot'].strip())
    pivot_params = elements.asDict()

stream = Stream(args['endpoint'],
                *probes,
                cache=1)

variables = []

for measurement_name in measurments:
    for table in measurments[measurement_name]:
        variables.append((measurement_name,table))

if len(variables) > 1:
    print('error: only one table variable allowed')
    exit(1)

model = \
    stream.model(*[stream.variable(x[0],x[1]) for x in variables],
                 by_tag=True)

stream.run()

event_prev = 0
df_prev = pd.DataFrame()
previous = defaultdict(lambda : defaultdict(list))

redraw = False
columns,_ = os.get_terminal_size(0)
pd.set_option('display.max_columns', None)
pd.set_option('display.width',columns)

def handler(signum, frame):
    global redraw
    columns,_ = os.get_terminal_size(0)
    pd.set_option('display.width',columns)
    redraw = True

signal.signal(signal.SIGWINCH, handler)

while True:
    df,event_cur,(_,timestamp) = model.data(ts=False)

    if event_cur != event_prev:
        current = defaultdict(lambda : defaultdict(list))

        df_out = pd.DataFrame()

        for row in df.itertuples(index=False):
            tag = row[0]

            for measurement_table in row[1:]:
                if isinstance(measurement_table,MeasurementTable):
                    table = defaultdict(list)

                    for measurement_table_row in measurement_table.rows:
                        table['_Publisher'].append(tag)

                        actual_values = []
                        for label,value in zip(measurement_table.labels,measurement_table_row.values):
                            actual_value = np.nan

                            if value.type == MeasurementTable.Measurement.TYPE_SINTEGER:
                                actual_value = value.iValue
                            elif value.type == MeasurementTable.Measurement.TYPE_UINTEGER:
                                actual_value = value.uValue
                            elif value.type == MeasurementTable.Measurement.TYPE_DOUBLE:
                                actual_value = value.dValue
                            else:
                                if value.sValue != 'NA':
                                    actual_value = value.sValue

                            actual_values.append(actual_value)

                        key = tuple([actual_values[x] for x in args['column_keys']])
                        current[tag][key] = actual_values

                        for index,(label,value) in enumerate(zip(measurement_table.labels,actual_values)):
                            if actions:
                                key = tuple([actual_values[x] for x in args['column_keys']])

                                if index in actions:
                                    for name,params in actions[index]:
                                        if 'col-name' in params:
                                            if params['col-name'][0] == '=':
                                                out_label = params['col-name'][1:]
                                            else:
                                                out_label = params['col-name'].replace('{}',label)
                                        else:
                                            out_label = label

                                        if name == 'pass':
                                            table[out_label].append(value)

                                        elif name == 'delta':
                                            if previous[tag][key]:
                                                if value >= previous[tag][key][index]:
                                                    table[out_label].append(value - previous[tag][key][index])
                                                else:
                                                    table[out_label].append(np.nan)
                                            else:
                                                table[out_label].append(np.nan)

                                        elif name == 'interval-average':
                                            if previous[tag][key]:
                                                current_samples = 0
                                                previous_samples = 0

                                                for n_col in params['sample-cols']:
                                                    current_samples += actual_values[n_col]
                                                    previous_samples += previous[tag][key][n_col]

                                                if previous_samples < current_samples:
                                                    table[out_label].append(((value * current_samples) - (previous[tag][key][index] * previous_samples)) / (current_samples - previous_samples))
                                                else:
                                                    table[out_label].append(np.nan)
                                            else:
                                                table[out_label].append(np.nan)
                            else:
                                # default pass all
                                table[label].append(value)

                    if df_out.empty:
                        df_out = pd.DataFrame.from_dict(table)
                    else:
                        df_out = pd.concat([df_out,pd.DataFrame.from_dict(table)],ignore_index=True)

        if not df_out.empty and pivot_params:
            column_names = df_out.columns
            df_out = pd.pivot_table(df_out,
                                    values=[column_names[x] for x in pivot_params['values']],
                                    columns=[column_names[x] for x in pivot_params['cols']],
                                    index=[column_names[x] for x in pivot_params['index']])

        print('\x1b[2J\x1b[H',
              time.strftime('%a, %d %b %Y %H:%M:%S ',
                            time.localtime(timestamp)),
              args['measurement-table'],
              ' \n',
              df_out if not df.empty else '',
              flush=True)

        previous = current
        event_prev = event_cur

    elif redraw:
        print('\x1b[2J\x1b[H',
              time.strftime('%a, %d %b %Y %H:%M:%S ',
                            time.localtime(timestamp)),
              args['measurement-table'],
              ' \n',
              df_out if not df.empty else '',
              flush=True)
        redraw = False

    time.sleep(1)
