#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from __future__ import print_function, unicode_literals, absolute_import

import os
import sys
import argparse

from . import __version__


def arg_parse():
    parser = argparse.ArgumentParser(description="View a tab-delimited file "
                                     "in a spreadsheet-like display. ")
    parser.add_argument('--version', action='version', version=__version__)
    parser.add_argument('filename', help="File to read. Use '-' to read from "
                        "the standard input instead.")
    parser.add_argument('--encoding', '-e', help="Encoding, if required.  "
                        "If the file is UTF-8, Latin-1(iso8859-1) or a few "
                        "other common encodings, it should be detected "
                        "automatically. If not, you can pass "
                        "'CP720', or 'iso8859-2', for example.")
    parser.add_argument('--delimiter', '-d', default=None,
                        help="CSV delimiter. Not typically necessary since "
                        "automatic delimiter sniffing is used.")
    parser.add_argument('--header', '-H', default=None, type=int,
                        help="Set number of header rows (defaults to 1)")
    parser.add_argument('--index', '-I', default=None, type=int,
                        help="Set number of index columns (defaults to 0)")
    parser.add_argument('--sheet', '-S', default=0, type=int,
                        help="Set the sheet index to read (defaults to 0)")
    parser.add_argument('--transpose', '-T', action='store_true',
                        help="Transpose the dataset.")
    parser.add_argument('--start_pos', '-s',
                        help="Initial cursor display position. "
                        "Single number for just y (row) position, or two "
                        "comma-separated numbers (--start_pos 2,3) for both. "
                        "Alternatively, you can pass the numbers in the more "
                        "classic +y:[x] format without the --start_pos label. "
                        "Like 'gtabview <fn> +5:10'. Negative offsets start "
                        "from the end of the dataset.")
    return parser.parse_known_args()


def start_position(start_norm, start_classic):
    """Given a string "[y, x, ...]" or a string "+[y]:[x]", return a tuple (y, x)
    for the start position

    Args: start_norm - string [y,x, ...]
          start_classic - string "+[y]:[x]"

    Returns: tuple (y, x)
    """
    if start_norm is not None:
        start_pos = start_norm.split(',')[:2]
        if not start_pos[0]:
            start_pos[0] = 0
        start_pos = [int(i) for i in start_pos]
    elif start_classic:
        sp = start_classic[0].strip('+').split(':')
        if not sp[0]:
            sp[0] = 0
        try:
            start_pos = (int(sp[0]), int(sp[1]))
        except IndexError:
            start_pos = (int(sp[0]), 0)
    else:
        start_pos = (0, 0)
    return start_pos


def fixup_stdin():
    print("gtabview: Reading from stdin...", file=sys.stderr)
    data = os.fdopen(os.dup(0), 'rb')
    os.dup2(os.open("/dev/tty", os.O_RDONLY), 0)
    return data


def main():
    args, extra = arg_parse()
    pos_plus = [i for i in extra if i.startswith('+')]
    start_pos = start_position(args.start_pos, pos_plus)
    if args.filename != '-':
        data = args.filename
    else:
        args.filename = "<stdin>"
        data = fixup_stdin()

    from gtabview import view
    try:
        view(data, enc=args.encoding, start_pos=start_pos, delimiter=args.delimiter,
             hdr_rows=args.header, idx_cols=args.index, sheet_index=args.sheet,
             transpose=args.transpose, metavar=args.filename)
    except KeyboardInterrupt:
        return 0
    except IOError as e:
        print("gtabview: {}".format(e))
        return 1

if __name__ == '__main__':
    sys.exit(main())
