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

import sys
import argparse

import anvio
import anvio.utils as utils
import anvio.terminal as terminal
import anvio.filesnpaths as filesnpaths
import anvio.interactive as interactive
from anvio.bottleroutes import BottleApplication

from anvio.errors import ConfigError, FilesNPathsError, DictIOError


__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__ = "Özcan Esen"
__email__ = "ozcanesen@gmail.com"
__requires__ = ['contigs-db']
__provides__ = ['contigs-stats', 'interactive', 'svg']

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

def write_stats_to_file(tables, output_file):
    filesnpaths.is_output_file_writable(output_file)
    output_table = [['contigs_db'] + tables['header']] + tables['basic_stats'] + tables['hmm'] + tables['scg']

    f = open(output_file, 'w')
    for line in output_table:
        f.write("%s\n" % "\t".join(map(str, line)))
    f.close()

    run.info("Output file", output_file)


if __name__ == '__main__':
    parser = argparse.ArgumentParser(description="Start the anvi'o interactive interactive for viewing or comparing contigs statistics")
    parser.add_argument('input', metavar = 'CONTIG DATABASE(S)', nargs='+',
                        help = "Anvio'o Contig databases to display statistics, \
                                you can give multiple databases by seperating them with space.")
    groupA = parser.add_argument_group('REPORT CONFIGURATION', "Specify what kind of output you want.")
    groupA.add_argument(*anvio.A('report-as-text'), **anvio.K('report-as-text'))
    groupA.add_argument(*anvio.A('output-file'), **anvio.K('output-file'))
    groupB = parser.add_argument_group('SERVER CONFIGURATION', "For power users.")
    groupB.add_argument(*anvio.A('ip-address'), **anvio.K('ip-address'))
    groupB.add_argument(*anvio.A('port-number'), **anvio.K('port-number'))
    groupB.add_argument(*anvio.A('browser-path'), **anvio.K('browser-path'))
    groupB.add_argument(*anvio.A('server-only'), **anvio.K('server-only'))
    groupB.add_argument(*anvio.A('password-protected'), **anvio.K('password-protected'))

    args = anvio.get_args(parser)
    A = lambda x: args.__dict__[x] if x in args.__dict__ else None

    try:
        if A('report_as_text'):
            if not A('output_file'):
                raise ConfigError("You set the --report-as-text flag but didn't give any --output-file. ")

        args.mode = 'contigs'
        d = interactive.ContigsInteractive(args)
        args.port_number = utils.get_port_num(args.port_number, args.ip_address, run=run)

        if A('output_file'):
            write_stats_to_file(d.tables, A('output_file'))

        if not A('report_as_text'):
            app = BottleApplication(d)
            app.run_application(args.ip_address, args.port_number)
    except ConfigError as e:
        print(e)
        sys.exit(-1)
    except FilesNPathsError as e:
        print(e)
        sys.exit(-2)
    except DictIOError as e:
        print(e)
        sys.exit(-3)
