#!/usr/bin/env python
#
#    Copyright (c) 2016, 2017 Timothy Savannah All Rights Reserved
#  under terms of the GPL version 2. You should have recieved a copy of this with distribution,
#  as LICENSE. You may also find the full text at https://github.com/kata198/popLines/LICENSE
#

#  This program turns files into queues. You can pop off a range of lines from a file
#   So your file can contain a list of items to process, and you can use this to pop off that queue.
#
#
#  You can also peek (not modify the source) with "--peek"

#vim: set ts=4 sw=4 expandtab
import os
import sys

from PopLines import popRange

def printUsage():
    sys.stderr.write('''Usage: popRange (Options) [start] [stop] (?step) [filename]

  Options:

     --peek        Perform the operation, but don't modify the source file


  Where step is optional (if omitted, assumed 1).

  Start and stop are 1-origin line numbers that form an inclusive range.
  
  The values can be negative, which represents number of lines from the last line ( -1 is last line, -2 is second-to-last...)

Step is the period, so a step of 1 is every element, 2 is every other...


Examples:
  popRange 1 -1 ,2 babies.txt > everyOtherBaby.txt

  popRange 3 5 items.txt > itemsThreeFourAndFive.txt
''')

if __name__ == '__main__':

    args = sys.argv[1:]

    if '--help' in args:
        printUsage()
        sys.exit(1)

    if '--peek' in args:
        saveChanges = False
        args.remove('--peek')
    else:
        saveChanges = True


    if len(args) not in (3, 4):
        sys.stderr.write('Wrong number of arguments.\n\n')
        printUsage()
        sys.exit(1)

    start = args[0]
    stop = args[1]
    if len(args) > 3:
        step = args[2]
    else:
        step = 1


    try:
        start = int(start)
        stop = int(stop)
        step = int(step)
    except:
        sys.stderr.write('Invalid range paramater. Should be one-origin integers.\n\n')
        printUsage()
        sys.exit(1)

    filename = args[-1]
    if not os.path.exists(filename):
        sys.stderr.write('No such file: %s\n' %(filename,))
        sys.exit(2)
    if not os.path.isfile(filename):
        sys.stderr.write('Not a file: %s\n' %(filename,))
        sys.exit(2)

    try:
        output = popRange(start, stop, step, filename, saveChanges)
    except Exception as e:
        sys.stderr.write('Error: %s\n' %(str(e,)))
        #raise e
        sys.exit(2)

    if len(output) > 0:
        sys.stdout.write('\n'.join(output))
        sys.stdout.write('\n')

