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

import sys
import argparse

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

from anvio.errors import ConfigError, FilesNPathsError


__author__ = "Developers of anvi'o (see AUTHORS.txt)"
__copyright__ = "Copyleft 2015-2018, the Meren Lab (http://merenlab.org/)"
__credits__ = []
__license__ = "GPL 3.0"
__version__ = anvio.__version__
__maintainer__ = "A. Murat Eren"
__email__ = "a.murat.eren@gmail.com"


run = terminal.Run()


def main(args):
    # this is how simple it is:
    profile_db = dbops.ProfileSuperclass(args)
    profile_db.init_gene_level_coverage_stats_dicts()

    print()

    gene_coverages = {}
    gene_detection = {}

    for gene_callers_id in profile_db.gene_level_coverage_stats_dict.keys():
        gene_coverages[gene_callers_id], gene_detection[gene_callers_id] = {}, {}

        for sample_name in profile_db.p_meta['samples']:
            gene_coverages[gene_callers_id][sample_name] = profile_db.gene_level_coverage_stats_dict[gene_callers_id][sample_name]['mean_coverage']
            gene_detection[gene_callers_id][sample_name] = profile_db.gene_level_coverage_stats_dict[gene_callers_id][sample_name]['detection']

    gene_coverages_output = args.output_file_prefix +  '-GENE-COVERAGES.txt'
    gene_detection_output = args.output_file_prefix +  '-GENE-DETECTION.txt'

    filesnpaths.is_output_file_writable(gene_coverages_output)

    utils.store_dict_as_TAB_delimited_file(gene_coverages, gene_coverages_output)
    utils.store_dict_as_TAB_delimited_file(gene_detection, gene_detection_output)

    run.info('Gene coverages', gene_coverages_output)
    run.info('Gene detection', gene_detection_output)


if __name__ == '__main__':
    parser = argparse.ArgumentParser(description='Export gene coverage and detection data from')

    parser.add_argument(*anvio.A('profile-db'), **anvio.K('profile-db'))
    parser.add_argument(*anvio.A('contigs-db'), **anvio.K('contigs-db'))
    parser.add_argument(*anvio.A('output-file-prefix'), **anvio.K('output-file-prefix', {'required': True}))

    args = anvio.get_args(parser)

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