#!/usr/bin/env python3
# this is to address a frustration with using awk and cut
# 12AUG21
# shyft

import argparse
import re
import codecs 
from rich import print
from rich.table import Table
from rich.console import Console



def unescaped_str(arg_str):
    return codecs.decode(str(arg_str), 'unicode_escape')

def get_lines():
    with open('/dev/stdin') as f:
        data = f.readlines()
    return data

def showCols(data, cols=[], delim=' ', skip_first=0, replace=''):
    #TODO IMPLEMENT THE REPLACE FUNCTIONALITY

    # delim = delim.replace(r'\\t', '\t' )
    if r'\x' in delim:
        delim = chr(int(delim[2:]))
    
    #print('delim = ', repr(delim.encode()))
    
    table = Table(expand=True,box=None, show_header=False, header_style=None)
    
    for _ in cols:
        table.add_column()
    out = []
    for line in data:
        line = line[:-1]  # same as above
        line = line.strip()
        # line = re.subn(f"{delim}",' ',line)[0]
        if line == '':
            continue
        
        if delim == ' ':
            line = line.split() # break the lines up based on some delimeter. default space
        else:
            line = line.split(delim)

        line = [x.strip() for x in line if x != ''] # filter out empty elements; replaces the conditional in the for block

        if args.hide == True:
            line = [ val for idx, val in enumerate(line,start=1) if idx not in cols ] 
        else:
            line = [ val for idx, val in enumerate(line, start=1) if idx in cols ]
        
        out.append(line)
    
    for line in out[skip_first:]:
        print(f'{delim}'.join(line))
        # print(*line)


def csv_int(string):
    # custom handling of a comma delimarated list of integers
    # https://www.tuxevara.de/2015/01/pythons-argparse-and-lists/
    seq = [int(x) for x in string.split(',') if x != '']
    # print(seq)
    return seq


if __name__ == '__main__':

    parser = argparse.ArgumentParser(description="this is to address a frustration with using awk and cut")
    parser.add_argument("cols", help="the columns you want to display", type=csv_int ) # custom handler
    parser.add_argument("--delim",'-d', help="delimiter string", default=' ', type=unescaped_str)
    parser.add_argument("--replace",'-r', help='replace X with Y: e.g. --replace "\\s \\t"  to replace all spaces with tabs', default='', type=str)
    parser.add_argument("--skip-first",'--skip', help="skip first N lines; omit a header", default=0, type=int)
    parser.add_argument("--not",'-n','--hide', dest='hide', action='store_true',  help="show all columns except these columns; hide these cols", default=False)


    args = parser.parse_args()
    
    data = get_lines()
    
    showCols(data, cols=args.cols, delim=args.delim, skip_first=args.skip_first)

