#!/usr/bin/python3

import sys, getopt
from datetime import datetime, date, time, tzinfo
import re
import math
import matplotlib.pyplot as plt

#sys.path.append('lib64')

#------------------------------------------------------------------------------	
def usage (script_name):
    print
    print " That script extracts only the Bid-Price Curve (BPC) from the log"
    print " file generated by the rmol binary. It then plots the"
    print " corresponding BPC."
    print
    print " Usage: %s [options]" % script_name
    print
    print "  -h, --help           : outputs help and quits"
    print "  -o, --output <path>  : path to output file (if blank, stdout)"
    print "  <path>               : input file"
    print "                         Default: 'rmol.log'"
    print "  -p, --plot           : plot (if blank, no plot is produced)"
    print

#------------------------------------------------------------------------------	
def handle_opt():
    try:
        opts, args = getopt.getopt(sys.argv[1:], "ho:p", 
                                   ["help", "output", "plot"])
    except getopt.GetoptError, err:
        # Will print something like "option -a not recognized"
        print str (err)
        usage (sys.argv[0])
        sys.exit (2)
	
    # Default options
    plotFlag = False
    input_filename = 'rmol.log'
    output_filename = ''
    input_file = sys.stdin
    output_file = sys.stdout

    # Input stream/file
    if len (args) != 0:
        input_filename = args[0]

    # Handling
    for o, a in opts:
        if o in ("-h", "--help"):
            usage (sys.argv[0])
            sys.exit()
        elif o in ("-o", "--output"):
            output_filename = a
        elif o in ("-p", "--plot"):
            plotFlag = True
        else:
            assert False, "Unhandled option"

    # Input file (BPC). That file is normally compressed
    # with GNU Zip (gzip)
    if (input_filename != ''):
	flag_gz = True
	if len (input_filename) < 2:
            flag_gz = False
	elif input_filename[-2:] != 'gz':
            flag_gz = False
	if flag_gz:
            input_file = gzip.open (input_filename, 'rb')
	else:
            input_file = open (input_filename, 'r')

    if (output_filename != ''):
        output_file = open (output_filename, 'w')

    #
    print "Produces a plot: " + str(plotFlag)
    print "Input stream/file: '" + input_filename + "'"
    print "Output stream/file: '" + output_filename + "'"
    return plotFlag, input_file, output_file

#------------------------------------------
def plot_simple(yVals):
    plt.plot(yVals,'b-o')
    plt.show()

#--------------------------------------------
def main():
    # Parse command options
    plotFlag, input_file, output_file = handle_opt()

    # Iterate while there is something to read from the file
    bkgIdx = 0

    # The O&D statistics holder is a dictionary made of:
    #  - a key, itself made of the origin, destination and flight departure date
    #  - the list of booking dates corresponding to all the booking requests
    OnDStatsHolder = {}

    # The O&D statistics object is a dictionary made of:
    #  - a key, itself made of the origin, destination and flight departure date
    #  - the cumulative number of booking requests made at the corresponding
    #    booking date for that key
    OnDStats = {}

    # Iterate while there are booking requests in the rmol.log file
    for line in input_file:
        # The lines of interest contain the "Bid-Price Vector" key-word
        matchedLine = re.search ("Bid-Price Vector", line)

        # If there is no match, the loop will continue on to the next line
        if not matchedLine:
            continue

        # There is a match. Now, the Bid-Price Vector (BPV) information will
        # be extracted
        extractor = re.compile ("^(?:.*Bid-Price Vector \(BPV\): )([0-9., ]+)+$")
        extractedList = extractor.search (line)
        bpcListString = extractedList.group(1)

        # DEBUG
        print ("Extracted list: " + str(extractedList))
        print ("1: " + bpcListString)

        # BPC
        bpc = bpcListString.split(', ')

        # DEBUG
        print bpc

    # Plot with MatplotLib
    if plotFlag:
        # Plot with solid line ('-') and blue ('b') circles ('o')
        plt.plot (bpc, linestyle='solid', marker='o')

    #
    output_file.write ("\n")

    # Plot with MatplotLib
    if plotFlag:
        plt.show()

#--------------------------------------------
if __name__ == "__main__":
    main()

