#!/usr/bin/env python

from __future__ import print_function

import argparse
import importlib
import os
import sys

import g2gtools.g2g
import g2gtools.g2g_commands

from g2gtools import __version__ as version

__author__ = "Matthew Vincent mvincent@jax.org"

ext_modules = ['pysam', 'bx.intervals']
failed_modules = []

logo_text = """

        ___       _              _
       |__ \     | |            | |
   __ _   ) |__ _| |_ ___   ___ | |___
  / _` | / // _` | __/ _ \ / _ \| / __|
 | (_| |/ /| (_| | || (_) | (_) | \__ \\
  \__, |____\__, |\__\___/ \___/|_|___/   v""" + version + """
   __/ |     __/ |
  |___/     |___/

"""

for dependency in ext_modules:
    try:
        importlib.import_module(dependency)
    except ImportError as ie:
        failed_modules.append(dependency)

if len(failed_modules) > 0:
    sys.stderr.write('Error: The following modules need to be installed: ')
    sys.stderr.write('\t' + ', '.join(failed_modules))
    sys.exit(1)


class G2GToolsApp(object):
    """
    The most commonly used commands are:
       vcf2vci       Creates VCI file from VCF file(s)
       patch         Replaces bases in a fasta file from SNPs specified in a VCI file
       transform     Incorporates indels specified in a VCI file
       convert       Lifts over coordinates
       extract       Gets subsequences from fasta file

    Other commands:
       gtf2db        Creates db file from GTF annotations

    """

    def __init__(self):
        self.script_name = os.path.basename(__file__)
        parser = argparse.ArgumentParser(add_help=False)

        def print_message(message):
            sys.stderr.write(logo_text)
            sys.stderr.write('\n')
            sys.stderr.write(message)
            sys.stderr.write('\n')
            sys.stderr.write(G2GToolsApp.__doc__)
            sys.stderr.write('\n')
            sys.exit(1)

        parser.error = print_message

        parser.add_argument('command', nargs='?', help='Subcommand to run')
        parser.add_argument("-h", "--help", dest="help", action="store_true")
        parser.add_argument("-v", "--version", dest="version", action="store_true")

        if len(sys.argv) == 1:
            g2gtools.g2g.exit("", parser)

        # parse_args defaults to [1:] for args, but need to exclude
        # the rest of the args too, or validation will fail
        args = parser.parse_args(sys.argv[1:2])

        if args.version:
            print(version)
            sys.exit(1)

        if args.help:
            g2gtools.g2g.exit("", parser)

        if not args.command:
            g2gtools.g2g.exit("", parser)

        if not hasattr(self, args.command):
            g2gtools.g2g.exit("Unrecognized command: {}".format(args.command), parser)

        # use dispatch pattern to invoke method with same name
        getattr(self, args.command)()

    def convert(self):
        g2gtools.g2g_commands.command_convert(sys.argv[2:], self.script_name + ' convert')

    def extract(self):
        g2gtools.g2g_commands.command_fasta_extract(sys.argv[2:], self.script_name + ' extract')

    def transform(self):
        g2gtools.g2g_commands.command_fasta_transform(sys.argv[2:], self.script_name + ' transform')

    def patch(self):
        g2gtools.g2g_commands.command_fasta_patch(sys.argv[2:], self.script_name + ' patch')

    def vcf2vci(self):
        g2gtools.g2g_commands.command_vcf2vci(sys.argv[2:], self.script_name + ' vcf2vci')

    def gtf2db(self):
        g2gtools.g2g_commands.command_gtf2db(sys.argv[2:], self.script_name + ' gtf2db')

    def parse(self):
        g2gtools.g2g_commands.command_parse_region(sys.argv[2:], self.script_name + ' parse')

    def fastaformat(self):
        g2gtools.g2g_commands.command_fastaformat(sys.argv[2:], self.script_name + ' fastaformat')

    def vciquery(self):
        g2gtools.g2g_commands.command_vciquery(sys.argv[2:], self.script_name + ' vciquery')

    def logo(self):
        print(logo_text)

if __name__ == '__main__':
    G2GToolsApp()

