###############################################################################
# Copyright (c) 2012 Trimble Navigation Ltd
# $Id: NoPiSD_Main.py,v 1.1 2012/02/04 01:08:47 shankar Exp $
###############################################################################
#
# NoPiSD_Main.py
#
# Top-level module to generate statistical trend plots for NoPi processing
# results The module supports five different ways to generate trend
# plots. Please refer to the README for example plots for each each method. 
#
# The desired method(s) can be passed as command line arguments when invoking
# this script. If no method is specified, the script generates plots necessary
# to populate a webpage which displays long term trends.
###############################################################################

import os
import sys
import datetime
import glob
import string

import matplotlib
matplotlib.use('agg')

from NoPiSD_Process import *
from NoPiSD_Load_Summary import cl_load_concat_summ
from NoPiSD_Web_Page import cl_web_page
from NoPiSD_Utils import add_utils_dir_to_path, show_help
add_utils_dir_to_path()

from NoPiUT_Common_Meas import *


# Ensure user has specified atleast datapath to concatenated mtb files
if ( len( sys.argv ) != 2 and len( sys.argv ) != 3 ) :
  show_help()
  sys.exit()

# Ensure the data path is valid and terminated with a directory slash
data_path = data_path_valid( sys.argv[1] )

# Load concatenation summary file
concat_summ = cl_load_concat_summ( data_path + 'concat_summary.txt' )

# Read fixed scale limits from file for each of the three baselines
load_axis_limits( concat_summ )

# If no specific method is specified, generate plots required to populate long
# term trends webpage
if ( len( sys.argv ) == 2 ) :

  print 'Generating per combo trends'
  gen_trends_method_2( concat_summ, data_path ) 
  print 'Generating top level trends'
  gen_trends_method_4( concat_summ, data_path )

  # Create the Trimble logo PNG file used by the web page
  create_logo_png()

  # Create a web directory if it does not exist
  if ( not( os.access( 'web', os.F_OK ) ) ) :
    print 'Create web directory'
    os.mkdir( 'web' )

  # Create web page to display results
  web_page = cl_web_page( concat_summ )
  web_page.input_data_file_section( concat_summ )
  web_page.create_baseline_links( concat_summ )

# Generate trend plots using user requested method(s)
elif ( len( sys.argv ) == 3 ) :
  plot_methods = parse_plot_method( sys.argv[2] )
  for method in plot_methods :
    # string.join uses whitespace as its default separator. Use
    # empty string instead to generate string which eval() will execute
    print 'Generating trends using method: %d' % method
    tmp_str = string.join( [ 'gen_trends_method_',
                             string.strip( str( method ) ),
                             '( concat_summ,'
                             ' data_path )' ],
                           ''
                          )
    eval( tmp_str )
