#!/usr/bin/python3
"""
@file ifciisubcolumn.py
@copyright ESO - European Southern Observatory
@defgroup iftest	
@brief IFTEST - Subsystem Interface Testing
Tool to extract a column data from a subscription to a shared vector in the cii file.
"""

import argparse
import subprocess
from asyncio.subprocess import DEVNULL

def main():

    example_text = '''example:
    ifciisubcolumn cii-m2_test-10_wh_mirror_cascade_20220914-104053.log outfile.dat main_sa_sttlm_lractuator_force --columns 0 3 5 --timezero --plot
    '''

    # Instantiate the parser
    parser = argparse.ArgumentParser(description='Extract data from a column of a given subscribed attribute in a cii log file.',
                                     epilog=example_text,
                                     formatter_class=argparse.RawDescriptionHelpFormatter)
    
    # Required URL, PATH and FILENAME
    parser.add_argument('file_in', type=str, help='CII log file. Example: cii_tests.log')
    parser.add_argument('file_out', type=str, help='Output file. Example: testdata.dat')
    parser.add_argument('attribute', type=str, help='Attribute to extract the data from. Example: main_sa_sttlm_lractuator_force')
    parser.add_argument('--columns', nargs='+', default=-1, type=int, help='Columns numbers to extract the data separated by space, starting from 0. Example: 0 2')
    parser.add_argument('--timezero', action='store_true', help='Set initial time to Zero.')
    parser.add_argument('--plot', action='store_true', help='Launch gnuplot of the data.')
    #parser.add_argument('--match',     type=str, help='Matching strings separated by comma (in quotes). Example:"node1,node2"')
    #parser.add_argument('-d','--data' ,nargs='+', help='Data to subscribe', required=True)

    # Parse input arguments
    args = parser.parse_args()

    # Server,browse node and filename from input data
    file_in   = args.file_in
    file_out  = args.file_out
    attribute = args.attribute
    columns   = args.columns
    timezero  = args.timezero
    makeplot  = args.plot

    # When the timezero switch is True we substract the
    # initial time from the source timestamp
    if timezero:
        zerotime = -1
    else:
        zerotime = 0

    # Read file
    with open(file_in) as fd_in:
        lines = fd_in.readlines()

    # Write file
    with open(file_out,'w') as fd_out:
        fd_out.write(attribute + '\n')
        #headerline = "time"
        #for i in columns:
        #    headerline += ' ' + 'col_'+str(i)
        #fd_out.write(headerline + '\n')

        for line in lines:
            if 'UPDATED' not in line or attribute not in line:
                continue
            linesplit = line.split()
            if zerotime == -1:
                zerotime = float(linesplit[9])

            if '[' in linesplit[11]:
                datacolumns  = linesplit[11].split('[')[1].rstrip(']').split(',')
            else:
                datacolumns  = linesplit[11].split()

            if columns == -1:
                columns = list(range(0,len(datacolumns)))
                headerline = "time"
                for i in columns:
                    headerline += ' ' + 'col_'+str(i)
                    fd_out.write(headerline + '\n')

            newline = str(float(linesplit[9]) - zerotime)
            for i in columns:
                newline += ' ' + datacolumns[i]
            fd_out.write(newline + '\n')

    # Plot
    if makeplot:
        for idx, i in enumerate(columns):
            if idx == 0:
                gnucmd = "set key outside ; plot \'{}\' using 1:{} with lines title \'Col_{}\'".format(file_out,(i+2),i)
            else:
                gnucmd += ",\'\' using 1:{} with lines title \'Col_{}\'".format((i+2),i)

        gnucmd += "; refresh"
        #print(gnucmd)
        print("Plotting...")

        cmdList = ['gnuplot','-p','-e',gnucmd]

        p = subprocess.Popen(cmdList, stdout = DEVNULL)
        p.wait()

if __name__ == "__main__":
    main()
