#!/usr/bin/env python
# -*- coding: utf-8
"""Returns sequences for a given list of gene caller ids"""

import sys

import anvio
import anvio.terminal as terminal
import anvio.filesnpaths as filesnpaths

from anvio.errors import ConfigError, FilesNPathsError
from anvio.dbops import ContigsSuperclass


__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):
    c = ContigsSuperclass(args)

    output_file_path = args.output_file if args.output_file else 'search_results.txt'
    filesnpaths.is_output_file_writable(output_file_path)

    gene_caller_ids_is_a_file = False
    try:
        filesnpaths.is_file_exists(args.gene_caller_ids)
        gene_caller_ids_is_a_file = True
    except:
        pass

    if gene_caller_ids_is_a_file:
        try:
            gene_caller_ids = [int(l.strip()) for l in open(args.gene_caller_ids).readlines()]
        except:
            raise ConfigError("The gene caller ids parameter (%s) you used matched a file name in this directory\
                                however, anvi'o couldn't make much sense of it :/ Anvi'o certainly hopes this\
                                error makes some sense to you." % args.gene_caller_ids)
            sys.exit()
    else:
        if args.gene_caller_ids:
            gene_caller_ids = [i.strip().split('\t')[0] for i in args.gene_caller_ids.split(args.delimiter)]
        else:
            gene_caller_ids = []

    c.gen_FASTA_file_of_sequences_for_gene_caller_ids(gene_caller_ids, args.output_file, args.wrap)


if __name__ == '__main__':
    import argparse

    parser = argparse.ArgumentParser(description='A script to get back sequences of a list of genes')

    parser.add_argument(*anvio.A('contigs-db'), **anvio.K('contigs-db'))
    parser.add_argument(*anvio.A('gene-caller-ids'), **anvio.K('gene-caller-ids'))
    parser.add_argument(*anvio.A('output-file'), **anvio.K('output-file', {'required': True}))
    parser.add_argument(*anvio.A('delimiter'), **anvio.K('delimiter'))
    parser.add_argument(*anvio.A('wrap'), **anvio.K('wrap'))


    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)
