#!/usr/bin/env python
# encoding: utf-8
'''
altimetry.tools.cdf_merge -- shortdesc

altimetry.tools.cdf_merge is a description

It defines classes_and_methods

@author:     user_name
            
@copyright:  2013 organization_name. All rights reserved.
            
@contact:    user_renaud.dussurget@gmail.com
'''

import sys
import os

from optparse import OptionParser
from altimetry.tools.nctools import nc

__all__ = []
__version__ = 0.1
__date__ = '2013-06-18'
__updated__ = '2013-06-18'

DEBUG = 0
TESTRUN = 0
PROFILE = 0

def main(argv=None):
    '''Command line options.'''
    
    program_name = os.path.basename(sys.argv[0])
    program_version = "v0.1"
    program_build_date = "%s" % __updated__
 
    program_version_string = '%%prog %s (%s)' % (program_version, program_build_date)
    #program_usage = '''usage: spam two eggs''' # optional - will be autogenerated by optparse
    program_longdesc = '''''' # optional - give further explanation about what the program does
    program_license = "Copyright 2013 Renaud Dussurget"
 
    if argv is None:
        argv = sys.argv[1:]
    try:
        # setup option parser
        parser = OptionParser(version=program_version_string, epilog=program_longdesc, description=program_license)
        parser.add_option("-v", "--verbose", dest="verbose", action="store", type="int", help="set verbosity level [default: %default]",default=0)
        parser.add_option("-l", "--use_local_dims", dest="use_local_dims", action="store_true", help="Use local netcdf dimensions [default: %default]",default=True)
        parser.add_option("-O", "--overwrite", dest="overwrite", action="store_true", help="Overwrite output file [default: %default]",default=False)
        parser.add_option("-f", "--format", dest="format", action="store", help="Output NetCDF format [default: %default]",default="NETCDF4")

        
        #Add kwargs!
        kwargs_keys=[]
        for a in argv :
            if a.startswith('--'):
                parser.add_option(a,dest=a.replace('--',''),action="store", help="Additional keyword to use with nctools [default: %default]")
#                parser.set_defaults(**{a.replace('--',''):False})
                kwargs_keys.append(a.replace('--',''))

        # set defaults
#        parser.set_defaults(verbose="4",use_local_dims="True")
        
        # process options
        (opts, args) = parser.parse_args(argv)
        
        if opts.verbose > 0:
            print("verbosity level = %d" % opts.verbose)
            
        if len(args) != 3 :
            raise Exception('Program needs 3 arguments') 
            
        # MAIN BODY #
        
    except Exception, e:
        indent = len(program_name) * " "
        sys.stderr.write(program_name + ": " + repr(e) + "\n")
        sys.stderr.write(indent + "  for help use --help")
        return 2

    #Get program arguments
    f1=args[0]
    f2=args[1]
    fout=args[2]
    
    #Get keyword arguments for nc
    kwargs={}
    for k in kwargs_keys :
        kwargs.update({k:eval(opts.__dict__.get(k))})
    
    ncr=nc(verbose=opts.verbose,use_local_dims=opts.use_local_dims)
    
    d1=ncr.load(f1,**kwargs)
    d2=ncr.load(f2,**kwargs)
    
    dout=d1.copy()
    for k in d2.keys():
        dout.update({k:d2.get(k)})
    
    attrStr=dout.get('_attributes',{})
    
    cmd=[os.path.basename(sys.argv[0])]
    for a in argv : cmd.append(a)
    attrStr.update({'history':attrStr.pop('history','') +' '.join(cmd)})
    dout.update({'_attributes':attrStr})
    ncr.write(dout,fout,clobber=opts.overwrite,format=opts.format)


if __name__ == "__main__":
    if DEBUG:
        sys.argv.append("-h")
    if TESTRUN:
        import doctest
        doctest.testmod()
    if PROFILE:
        import cProfile
        import pstats
        profile_filename = 'altimetry.tools.cdf_merge_profile.txt'
        cProfile.run('main()', profile_filename)
        statsfile = open("profile_stats.txt", "wb")
        p = pstats.Stats(profile_filename, stream=statsfile)
        stats = p.strip_dirs().sort_stats('cumulative')
        stats.print_stats()
        statsfile.close()
        sys.exit(0)
    
    sys.exit(main())
