#!/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 2016"
__credits__ = ["Donovan Parks"]
__license__ = "GPL3"
__maintainer__ = "Donovan Parks"
__email__ = "donovan.parks@gmail.com"
__status__ = "Development"

import os
import sys
import tempfile
import argparse

from drawm import version
from drawm.main import OptionsParser

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


def print_help():
    """Help menu."""

    print ''
    print '                ...::: DrawM v' + version() + ' :::...'''
    print '''\

    Tree drawing:
     draw -> Create SVG image of a phylogenetic tree in Newick format

    Tree manipulation:
     reroot  -> Reroot tree at mid-point or using an outgroup
     prune   -> Prune tree to a specific set of extant taxa
     subtree -> Extract lineage from tree
     rename  -> Change taxa labels in tree
     convert -> Convert file format of a phylogenetic tree 

  Use: drawm <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/refinem).
    '''

if __name__ == '__main__':

    # initialize the options parser
    parser = argparse.ArgumentParser(add_help=False)
    subparsers = parser.add_subparsers(help="--", dest='subparser_name')
    
    # Draw command
    draw_parser = subparsers.add_parser('draw',
                                            formatter_class=CustomHelpFormatter,
                                            description='Create SVG image of a phylogenetic tree.')
    draw_parser.add_argument('input_tree', help='input tree in Newick format')
    draw_parser.add_argument('config_file', help='file specifying location of visual property files')
    draw_parser.add_argument('output_prefix', help='prefix for output files')
    draw_parser.add_argument('--width', help='width of image in inches', type=float, default=6.5)
    draw_parser.add_argument('--height', help='height of image in inches', type=float, default=6.5)
    draw_parser.add_argument('--dpi', help='resolution of image (dots per inch)', type=int, default=600)
    draw_parser.add_argument('--silent', help="suppress output of logger", action='store_true')
    
    # Reroot command
    reroot_parser = subparsers.add_parser('reroot',
                                            formatter_class=CustomHelpFormatter,
                                            description='Reroot tree at mid-point or using an outgroup.')
    reroot_parser.add_argument('input_tree', help='input tree in Newick format')
    reroot_parser.add_argument('output_tree', help='rerooted output tree')
    reroot_parser.add_argument('--midpoint', help='width of image in inches', action='store_true')
    reroot_parser.add_argument('--outgroup', nargs='*', help='taxa comprising outgroup')
    reroot_parser.add_argument('--silent', help="suppress output of logger", action='store_true')
    
    # Prunt command
    prune_parser = subparsers.add_parser('prune',
                                            formatter_class=CustomHelpFormatter,
                                            description='Prune tree to a specific set of extant taxa.')
    prune_parser.add_argument('input_tree', help='input tree in Newick format')
    prune_parser.add_argument('taxa_to_retain', help='input file specify taxa to retain')
    prune_parser.add_argument('output_tree', help='pruned output tree')
    prune_parser.add_argument('--silent', help="suppress output of logger", action='store_true')
    
    # Subtree command
    subtree_parser = subparsers.add_parser('subtree',
                                            formatter_class=CustomHelpFormatter,
                                            description='Extract lineage from treeusing an outgroup.')
    subtree_parser.add_argument('input_tree', help='input tree in Newick format')
    subtree_parser.add_argument('output_tree', help='output subtree')
    subtree_parser.add_argument('subtree_taxa', nargs='*', help='taxa specifying subtree')
    subtree_parser.add_argument('--silent', help="suppress output of logger", action='store_true')
    
    # Rename command
    rename_parser = subparsers.add_parser('rename',
                                            formatter_class=CustomHelpFormatter,
                                            description='Change taxa labels in tree.')
    rename_parser.add_argument('input_tree', help='input tree in Newick format')
    rename_parser.add_argument('taxa_label_map', help='file specifying taxa to rename')
    rename_parser.add_argument('output_tree', help='output tree')
    rename_parser.add_argument('--silent', help="suppress output of logger", action='store_true')
    
    # Convert command
    convert_parser = subparsers.add_parser('convert',
                                            formatter_class=CustomHelpFormatter,
                                            description='Convert file format of a phylogenetic tree.')
    convert_parser.add_argument('input_tree', help='input tree')
    convert_parser.add_argument('input_format', choices=['newick', 'nexus', 'nexml'], help='file format of input tree')
    convert_parser.add_argument('output_format', choices=['newick', 'nexus', 'nexml'], help='file format of output tree')
    convert_parser.add_argument('output_tree', help='output tree')
    convert_parser.add_argument('--silent', help="suppress output of logger", 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()

    try:
        logger_setup(args.output_dir, "drawm.log", "DrawM", version(), args.silent)
    except:
        logger_setup(None, "drawm.log", "DrawM", 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
