#!/usr/bin/env python
# -*- coding: utf-8

import os
import sys

import anvio
import anvio.tables as t
import anvio.dbops as dbops
import anvio.utils as utils
import anvio.terminal as terminal

from anvio.errors import ConfigError, FilesNPathsError

__author__ = "A. Murat Eren"
__copyright__ = "Copyright 2015, The anvio Project"
__credits__ = []
__license__ = "GPL 3.0"
__version__ = anvio.__version__
__maintainer__ = "A. Murat Eren"
__email__ = "a.murat.eren@gmail.com"
__status__ = "Development"


run = terminal.Run()

def main(args):
    annotation_db = dbops.AnnotationDatabase(args.db_path)
    genes_contigs_table = annotation_db.db.get_table_as_dict(t.genes_contigs_table_name)
    genes_contigs_table_headers = annotation_db.db.get_table_structure(t.genes_contigs_table_name)
    utils.store_dict_as_TAB_delimited_file(genes_contigs_table, args.output, genes_contigs_table_headers)
    run.info('Recovered matrix', os.path.abspath(args.output))

if __name__ == '__main__':
    import argparse
    parser = argparse.ArgumentParser(description='Generate a TAB-delimited matrix file from genes tables found in an\
                                                  annotation database')
    parser.add_argument('db_path', metavar = 'DB_PATH', default = None,
                        help = 'Path to the annotation database.')
    parser.add_argument('-o', '--output', default = "ANNOTATION.txt",
                        help = 'Output file path. Default is %(default)s.')

    args = parser.parse_args()

    try:
        main(args)
    except ConfigError, e:
        print e
        sys.exit(-1)
    except FilesNPathsError, e:
        print e
        sys.exit(-2)
