#!/opt/anaconda1anaconda2anaconda3/bin/python
# -*- coding: utf-8

import sys

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

from anvio.errors import ConfigError, FilesNPathsError


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


run = terminal.Run()
progress = terminal.Progress()


def main(args):
    dbops.is_contigs_db(args.contigs_db)

    if not args.output_file:
        raise ConfigError("You should provide an output file name so anvi'o does not have to make up a silly\
                            name :/")

    filesnpaths.is_output_file_writable(args.output_file)

    contigs_db = dbops.ContigsSuperclass(args)

    if not contigs_db.genes_in_contigs_dict:
        raise ConfigError("Something weird happened. The contigs database does not seem to have any gene calls :/")
    else:
        run.info('Num gene calls found', len(contigs_db.genes_in_contigs_dict))

    utils.store_dict_as_TAB_delimited_file(contigs_db.genes_in_contigs_dict, args.output_file, headers=t.genes_in_contigs_table_structure)

    run.info('Output', args.output_file)


if __name__ == '__main__':
    import argparse

    parser = argparse.ArgumentParser(description="Export gene calls from an anvi'o contigs database.")

    parser.add_argument(*anvio.A('contigs-db'), **anvio.K('contigs-db'))
    parser.add_argument(*anvio.A('output-file'), **anvio.K('output-file'))

    args = parser.parse_args()

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