#!/usr/bin/env python
# -*- coding: utf-8
"""Gives you back items in a collection.

   Output files can directly be used by anvi-import-collection"""

import sys
import argparse

import anvio
import anvio.dbops as dbops
import anvio.terminal as terminal
import anvio.ccollections as ccollections

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_profile_db(args.profile_db)

    c = ccollections.Collections(r = run, p = progress)
    c.populate_collections_dict(args.profile_db, anvio.__profile__version__)

    if args.list_collections:
        c.list_collections()
        sys.exit()

    if not args.collection_name:
        raise ConfigError, "You must declare a colection name. Use --list-collections flag\
                            to list available ones."

    if args.collection_name not in c.collections_dict:
        raise ConfigError, "Are you sure collection name '%s' stored in this database? You know,\
                            probably it is not at all :/ You can always use --list-collections\
                            flag to see what is in there." % args.collection_name

    # {'read_only': False, 'source_db_path': 'delete.db', 'num_splits': 1453, 'source_db_version': '13', 'bin_names': 'Bin_1', 'num_bins': 1}
    collection_info = c.collections_dict[args.collection_name]
    run.info('Collection found', '"%s" (%d items in %d bins)' % (args.collection_name, collection_info['num_splits'], collection_info['num_bins']))

    c.export_collection(args.collection_name, args.output_file_prefix)


if __name__ == '__main__':
    parser = argparse.ArgumentParser(description="Export a collection from an anvi'o database")

    parser.add_argument(*anvio.A('profile-db'), **anvio.K('profile-db'))
    parser.add_argument(*anvio.A('collection-name'), **anvio.K('collection-name'))
    parser.add_argument(*anvio.A('output-file-prefix'), **anvio.K('output-file-prefix'))
    parser.add_argument(*anvio.A('list-collections'), **anvio.K('list-collections'))

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