#!/usr/bin/env python3

"""Simple XLSX reporting tool."""

import argparse
import os.path as path

from contextlib import closing
from glob import glob

from datasimple.cli import log
from datasimple.xl import load_ro_workbook


def main():
    """Entry point."""
    parser = argparse.ArgumentParser()
    parser.add_argument(
        'files', metavar='X',
        help='XLSX file(s) to read - can include glob patterns',
        type=str,
        nargs='+'
    )
    parser.add_argument(
        '-d', '--dimensions',
        help='Show dimensions (may take a very long time for some workbooks)',
        default=False,
        action='store_true'
    )
    args = parser.parse_args()

    files = sorted(set([fn for arg in args.files for fn in glob(arg)]))
    if not files:
        raise ValueError('No files specified')
    for fn in files:
        if not path.isfile(fn):
            raise ValueError('{} does not exist!', fn)

    if args.dimensions:
        def output(name, wb):
            ws = wb[name]
            dims = ws.calculate_dimension(force=True)  # will also calc min/max r/c
            log(
                '[!c]{}[!/c] (dims: {}, [!g]{:,d}[!/g] rows and [!g]{:,d}[!/g] cols)',
                name,
                dims,
                (ws.max_row - ws.min_row) + 1,
                (ws.max_column - ws.min_column) + 1,
            )
    else:
        # Easy to report without dimensions
        def output(name, wb):
            log('[!c]{}[!/c]', name)

    # Now we can actually process
    for fn in files:
        log('[!y]{}[!/y]', fn)
        with closing(load_ro_workbook(fn)) as wb:
            names = [str(i) for i in wb.sheetnames]
            for name in names:
                output(name, wb)


if __name__ == '__main__':
    main()
