#! /usr/bin/env python3
"""Show some lines from files

Usage: %(prog)s [options] [files]

"""

import sys

from pysyte import __version__
from pysyte.cli import streams
from pysyte.cli.functions import parser
from pysyte.cli.main import run
from pysyte.types import lines


def add_args(parser_):
    """Parse out command line arguments"""
    p = parser(parser_)
    p.positional('files', help='files to show (or "-" for stdin)')
    p.string('-a', '--at', default="", help='Show line at the line number')
    p.string('-f', '--first', default="1",
               help='number/regexp of first line to show')
    p.string('-l', '--last', default="0",
               help='number/regexp of last line to show')
    p.boolean('-p', '--paste', help='Paste text from clipboard')
    p.boolean('-i', '--stdin', help='Wait for text from stdin')
    p.lines()
    p.version()
    return p


def fill_arg(arg):
    at = 0
    if not arg:
        return 0
    try:
        return int(arg)
    except TypeError:
        return arg


def main(args):
    """Run the script"""
    at = fill_arg(args.at)
    first = fill_arg(args.first) or 1
    last = fill_arg(args.last) or -1
    main_screen = True
    for stream in streams.args(args, 'files'):
        start, lines_in = lines.first_and_rest(stream, at, first, last)
        lines_out = args.sed(lines_in, start)
        if main_screen and len(lines_out) > 40:
            main_screen = False
            args.alt_screen()
        print(lines.as_text(lines_out))
    return True


run(main, add_args)
