#!/usr/bin/env python
# -*- coding: utf-8
"""Takes a database and a table name as parameters, stores the content as
a TAB-delimited matrix."""

import sys

import anvio
import anvio.db as db
import anvio.utils as utils
import anvio.filesnpaths as filesnpaths
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"


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


def main(args):
    filesnpaths.is_file_exists(args.db_path)
    database = db.DB(args.db_path, None, ignore_version=True)
    tables_in_database = database.get_table_names()

    if args.list and not args.table:
        for table in tables_in_database:
            print table
        sys.exit()


    if not args.table:
        raise ConfigError, "You must specify a table name."

    if args.table not in tables_in_database:
        raise ConfigError, "Table '%s' is not seem to be in this databse :/" % args.table

    run.info('Database', '"%s" has been initiated with its %d tables.' % (args.db_path, len(tables_in_database)))

    table_content = database.get_table_as_dict(args.table)
    table_columns = database.get_table_structure(args.table)
    run.info('Table', '"%s" has been read with %d entries and %d columns.' % (args.table, len(table_content), len(table_columns)))

    if args.list:
        run.info('Table columns', '"%s"' % ', '.join(table_columns))
        sys.exit()

    if args.fields:
        fields_of_interest = [f.strip() for f in args.fields.split(',')]
        table_columns = [f for f in table_columns if f in fields_of_interest]

        if not len(table_columns):
            raise ConfigError, "None of the fields you are interested in are in the table header..." 

        run.info('Columns to report', '"%s"' % ', '.join(table_columns))


    if not args.output_file:
        args.output_file = args.table + '.txt'

    utils.store_dict_as_TAB_delimited_file(table_content, args.output_file, table_columns)
    run.info('Output', args.output_file)


if __name__ == '__main__':
    import argparse
    parser = argparse.ArgumentParser(description="Export anvi'o database tables as TAB-delimited text files.")

    parser.add_argument('db_path', metavar = 'DB',
                        help = "Anvi'o database to read from.")

    parser.add_argument(*anvio.A('table'), **anvio.K('table'))
    parser.add_argument(*anvio.A('list'), **anvio.K('list'))
    parser.add_argument(*anvio.A('fields'), **anvio.K('fields'))
    parser.add_argument(*anvio.A('output-file'), **anvio.K('output-file'))

    args = parser.parse_args()

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