#!/Users/victor/development/scripts/venv/bin/python
import argparse
import sys
import jtutils
import pcsv.any2csv
import io

def readCL():
    parser = argparse.ArgumentParser()
    parser.add_argument("-s","--xls_sheet", default="0", help="either sheet number or sheet name")
    parser.add_argument("--path", help="comma separated path string for json or xml. Example: 0,2,1")
    parser.add_argument("--summary", action="store_true", help="print summary information about json or xml: just the tags and depths")
    parser.add_argument("infile", nargs="?")
    args = parser.parse_args()
    if not args.path:
        args.path = []
    else:
        args.path = args.path.split(",")

    return args.infile, args.xls_sheet, args.path, args.summary

if __name__ == "__main__":
    infile, xls_sheet, path, summary = readCL()
    jtutils.fix_broken_pipe()

    standard_in = sys.stdin.buffer if sys.version_info[0] == 3 else sys.stdin

    if infile is None:
        infile = standard_in

    with io.open(infile, mode='rb') if infile != standard_in else standard_in as fin:
        txt = fin.read()
        if not txt:
            sys.stderr.write("ERROR: empty input found. Exiting..." + "\n")
            sys.exit(-1)
        pcsv.any2csv.any2csv(txt, xls_sheet=xls_sheet, path=path, summary=summary, to_stdout=True)
