#!/usr/bin/env python
import argparse,os
from minpower import solve,config
from minpower.tests import test

parser = argparse.ArgumentParser(description='Minpower command line interface')
parser.add_argument('directory', type=str, 
                   help='the direcory of the problem you want to solve (or name of minpower demo case)')
parser.add_argument('--solver','-s',  type=str, default=config.optimization_solver,
                   help='the solver name used to solve the problem (e.g. cplex, gurobi, glpk)')
parser.add_argument('--visualization_off','-v',action="store_true", default=False,
                  help='flag to turn off the visualization of the solution')
parser.add_argument('--breakpoints','-b',  type=int, default=config.default_num_breakpoints,
                   help='number of breakpoints to use in piece-wise linearization of polynomial costs')
parser.add_argument('--commitment_hours','-c', type=int, default=config.default_hours_commitment,
                   help='number hours per commitment in a rolling UC (exclusive of overlap)')
parser.add_argument('--overlap_hours','-o', type=int, default=config.default_hours_commitment_overlap,
                   help='number hours to overlap commitments in a rolling UC')      
parser.add_argument('--problemfile','-p',action="store_true", default=False,
                   help='flag to write the problem formulation to a problem-formulation.lp file -- useful for debugging')
parser.add_argument('--duals_off','-u',action="store_true", default=False,
                  help='flag to skip getting the the duals, or prices, of the optimization problem')
parser.add_argument('--dispatch_decommit_allowed','-d', action="store_true", default=False,
                    help='flag to allow de-commitment of units in an ED -- useful for getting initial conditions for UCs')
parser.add_argument('--logfile','-l',type=str,default=False,
                   help='log file, default is to log to terminal')
parser.add_argument('--solution_file',type=str,default=False,
                   help='save solution file to disk')
parser.add_argument('--profile',action="store_true",default=False,help='run cProfile and output to minpower.profile')
                    
#figure out the command line arguments
args = parser.parse_args()

directory=args.directory

if not os.path.isdir(directory):
    #check to see if the name is a minpower test case
    test_dir=os.path.join(os.path.dirname(test.__file__),directory)
    if os.path.isdir(test_dir):
        print 'solving test case: {}'.format(directory)
        directory = test_dir
    else:
        #otherwise raise error
        msg='There is no folder named "{}".'.format(directory)
        raise OSError(msg)


#import cProfile
#def profileit(filename):
#    '''a decorator for profiling'''
#    def inner(func):
#        def wrapper(*args, **kargs):
#            prof = cProfile.Profile()
#            retval = prof.runcall(func, *args, **kwargs)
#            # Note use of name from outer scope
#            prof.dump_stats(filename)
#            return retval
#        return wrapper
#    return inner


inputs=dict(solver=args.solver,
          num_breakpoints=args.breakpoints,
          hours_commitment=args.commitment_hours,
          hours_commitment_overlap=args.overlap_hours,
          dispatch_decommit_allowed=args.dispatch_decommit_allowed,
          visualization=not args.visualization_off,
          get_duals=not args.duals_off,
          problemfile=args.problemfile,
          logging_file=args.logfile,
          solution_file=args.solution_file)
if args.profile:
    print 'run profile'
    import cProfile
    prof = cProfile.Profile()
    prof.runcall(solve.problem, directory, **inputs)
    prof.dump_stats('minpower.profile')

else:
    #solve the problem with those arguments
    solve.problem(directory,**inputs)
