#!/srv/sw/python/2.7.4/bin/python

###############################################################################
#                                                                             #
#    This program is free software: you can redistribute it and/or modify     #
#    it under the terms of the GNU General Public License as published by     #
#    the Free Software Foundation, either version 3 of the License, or        #
#    (at your option) any later version.                                      #
#                                                                             #
#    This program is distributed in the hope that it will be useful,          #
#    but WITHOUT ANY WARRANTY; without even the implied warranty of           #
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the            #
#    GNU General Public License for more details.                             #
#                                                                             #
#    You should have received a copy of the GNU General Public License        #
#    along with this program. If not, see <http://www.gnu.org/licenses/>.     #
#                                                                             #
###############################################################################

__author__ = "Donovan Parks"
__copyright__ = "Copyright 2017"
__credits__ = ["Donovan Parks"]
__license__ = "GPL3"
__maintainer__ = "Donovan Parks"
__email__ = "donovan.parks@gmail.com"
__status__ = "Development"

import os
import sys
import ntpath
import logging
import tempfile
import argparse

from viewm.main import OptionsParser

from biolib.common import make_sure_path_exists
from biolib.logger import logger_setup
from biolib.misc.custom_help_formatter import ChangeTempAction, CustomHelpFormatter

def version():
    import viewm
    version_file = open(os.path.join(viewm.__path__[0], 'VERSION'))
    return version_file.read().strip()


def print_help():
    print ''
    print '                ...::: ViewM v' + version() + ' :::...'''
    print '''\

    draw -> Visualize functional modules expressed as KEGG-style logical expressions

  Use: viewm <command> -h for command specific help.

  Feature requests or bug reports can be sent to Donovan Parks (donovan.parks@gmail.com)
    or posted on GitHub (https://github.com/dparks1134/viewm).
    '''

if __name__ == '__main__':

    # initialize the options parser
    parser = argparse.ArgumentParser(add_help=False)
    subparsers = parser.add_subparsers(help="--", dest='subparser_name')

    # identify genes within genomes
    draw_parser = subparsers.add_parser('draw',
                                        formatter_class=CustomHelpFormatter,
                                        description='Visualize functional modules.')
    draw_parser.add_argument('input_genomes', help="genome files to process")
    draw_parser.add_argument('output_dir', help="output directory")
    draw_parser.add_argument('-x', '--file_ext', default='fna', help="extension of files to process")
    draw_parser.add_argument('--silent', help="suppress output", action='store_true')

    # get and check options
    args = None
    if(len(sys.argv) == 1 or sys.argv[1] == '-h' or sys.argv == '--help'):
        print_help()
        sys.exit(0)
    else:
        args = parser.parse_args()
       
    if hasattr(args, 'output_dir'):
        logger_setup(args.output_dir, "viewm.log", "ViewM", version(), args.silent)
    else:
        logger_setup(None, "viewm.log", "ViewM", version(), args.silent)

    # do what we came here to do
    try:
        parser = OptionsParser()
        if(False):
            # import pstats
            # p = pstats.Stats('prof')
            # p.sort_stats('cumulative').print_stats(10)
            # p.sort_stats('time').print_stats(10)
            import cProfile
            cProfile.run('parser.parse_options(args)', 'prof')
        elif False:
            import pdb
            pdb.run(parser.parse_options(args))
        else:
            parser.parse_options(args)
    except SystemExit:
        print "\n  Controlled exit resulting from an unrecoverable error or warning."
    except:
        print "\nUnexpected error:", sys.exc_info()[0]
        raise
