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

import sys
import argparse

import anvio
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):
    profile_db = dbops.ProfileSuperclass(args)

    gene_coverages_path = args.output_file_prefix +  '-GENE-COVERAGES.txt'
    gene_detection_path = args.output_file_prefix +  '-GENE-DETECTION.txt'

    filesnpaths.is_output_file_writable(gene_coverages_path)
    filesnpaths.is_output_file_writable(gene_detection_path)

    gene_coverages_file = open(gene_coverages_path, 'w')
    gene_detection_file = open(gene_detection_path, 'w')

    header_coverages = ['key'] + profile_db.p_meta['samples']
    header_detection = ['key'] + profile_db.p_meta['samples']

    gene_coverages_file.write('\t'.join(header_coverages) + '\n')
    gene_detection_file.write('\t'.join(header_detection) + '\n')

    def write_to_file():
        for gene_callers_id in profile_db.gene_level_coverage_stats_dict:
            line_coverages = [gene_callers_id]
            line_detection = [gene_callers_id]

            for sample_name in profile_db.p_meta['samples']:
                line_coverages.append(profile_db.gene_level_coverage_stats_dict[gene_callers_id][sample_name]['mean_coverage'])
                line_detection.append(profile_db.gene_level_coverage_stats_dict[gene_callers_id][sample_name]['detection'])

            gene_coverages_file.write('\t'.join(map(str, line_coverages)) + '\n')
            gene_detection_file.write('\t'.join(map(str, line_detection)) + '\n')

        profile_db.gene_level_coverage_stats_dict = {}
        profile_db.split_coverage_values_per_nt_dict = {}

    profile_db.init_gene_level_coverage_stats_dicts(callback=write_to_file, callback_interval=1000)

    gene_coverages_file.close()
    gene_detection_file.close()

    run.info('Gene coverages', gene_coverages_path)
    run.info('Gene detection', gene_detection_path)


if __name__ == '__main__':
    parser = argparse.ArgumentParser(description='Export gene coverage and detection data for all genes associated with\
                                                  contigs described in a profile database.')

    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)
