#!/usr/bin/env python3
import click
import sys
import os
import json
from sys import argv
from xlparser import *

if len(argv) <= 1:
    quit("xlparser --help")

if '-d' in argv:
    debug = print
else:
    debug = lambda *arg: 1


@click.command()
@click.argument('args', nargs=-1)
def main(args):
    """
    Usage: 
        xlparser [options] INFILE [OUTFILE]\n
            options:\n
                -h       For help.\n
        # From xlsx to csv.\n
        $ xlparser source.xlsx new.csv \n

        # From csv to xlsx.\n
        $ xlparser source.csv new.xlsx \n

        # From csv to json.\n
        $ xlparser source.csv new.json\n

        # From csv to stdout.\n
        $ xlparser source.xlsx | head \n
    """
    if len(args)<=1:
        args = args[0],'-'
    file, outfile, *_ = args
    rows = parse(file)
    debug(f'Convert xlsx from {argv[1]}')

    if outfile.endswith('.json'):
        json.dump(list(rows), open(outfile,'w'), ensure_ascii=False)
    elif outfile.endswith('.xlsx'):
        saveXlsx(rows, outfile)
    else:
        if outfile == '-': 
            outfile = sys.stdout
        saveCsv(rows, outfile)
    sys.stderr.write('\033[94m Done!\033[0m\n')

if __name__ == '__main__':
    main()
