#!/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 random elements within a given 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 popRandom

def printUsage():
    sys.stderr.write('''Usage: popRandom (Options) [number of lines] [filename]

  Options:

     --peek        Perform the operation, but don't modify the source file
     --ordered     Ensure the resulting random lines are output in the same order they appear in the file,
                     i.e. if your random lines picked are [5, 1] and this is present, you'll get [1, 5]
                     in the output, otherwise you'll get [5, 1]

Removes the given number of lines from a random selection within the provided file, returning on stdout.

Use this program to turn a list into a queue.
''')

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 '--ordered' in args:
        keepOrdered = True
        args.remove('--ordered')
    else:
        keepOrdered = False

    if len(args) != 2:
        sys.stderr.write('Wrong number of arguments.\n\n')
        printUsage()
        sys.exit(1)

    numLines = args[0]
    if not numLines.isdigit():
        sys.stderr.write('Number of lines (second argument) must be an integer.\n\n')
        printUsage()
        sys.exit(1)

    numLines = int(numLines)

    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 = popRandom(numLines, filename, keepOrdered, 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')

