#!/usr/bin/env python
# -*- coding: utf-8
"""Further analyze one or more bins in a collection.

   This is especially useful when there are one or more highly contaminated
   bins in a merged profile.
"""

import os
import sys
import json
import argparse
import webbrowser
import random

from multiprocessing import Process
from bottle import route, static_file, redirect, request, BaseRequest, response
from bottle import run as run_server

import anvio
import anvio.utils as utils
import anvio.refine as refine
import anvio.terminal as terminal
import anvio.bottleroutes as routes

from anvio.errors import ConfigError, FilesNPathsError, DictIOError, SamplesError


__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()


# get the absolute path for static directory under anvio
static_dir = os.path.join(os.path.dirname(utils.__file__), 'data/interactive')


parser = argparse.ArgumentParser(description="Start the anvi'o interactive interactive for refining")

groupA = parser.add_argument_group('DEFAULT INPUTS', "The interavtive interface can be started with and without\
                                                      anvi'o databases. The default use assumes you have your\
                                                      profile and contigs database, however, it is also possible\
                                                      to start the interface using ad-hoc input files. See 'MANUAL\
                                                      INPUT' section for other set of parameters that are mutually\
                                                      exclusive with datanases.")
groupB = parser.add_argument_group('REFINE-SPECIFICS', "Parameters that are essential to the refinement process.")
groupC = parser.add_argument_group('ADDITIONAL STUFF', "Parameters to provide additional layers, views, or layer data.")
groupD = parser.add_argument_group('VISUALS RELATED', "Parameters that give access to various adjustements regarding\
                                                       the interface.")
groupE = parser.add_argument_group('SWEET PARAMS OF CONVENIENCE', "Parameters and flags that are not quite essential (but\
                                                                   nice to have).")
groupF = parser.add_argument_group('SERVER CONFIGURATION', "For power users.")

groupA.add_argument(*anvio.A('profile-db'), **anvio.K('profile-db'))
groupA.add_argument(*anvio.A('contigs-db'), **anvio.K('contigs-db'))
groupA.add_argument(*anvio.A('samples-information-db'), **anvio.K('samples-information-db'))
groupB.add_argument(*anvio.A('collection-name'), **anvio.K('collection-name'))
groupB.add_argument(*anvio.A('bin-id'), **anvio.K('bin-id'))
groupB.add_argument(*anvio.A('bin-ids-file'), **anvio.K('bin-ids-file'))
groupC.add_argument(*anvio.A('additional-view'), **anvio.K('additional-view'))
groupC.add_argument(*anvio.A('additional-layers'), **anvio.K('additional-layers'))
groupD.add_argument(*anvio.A('split-hmm-layers'), **anvio.K('split-hmm-layers'))
groupD.add_argument(*anvio.A('show-outlier-snvs'), **anvio.K('show-outlier-snvs'))
groupE.add_argument(*anvio.A('dry-run'), **anvio.K('dry-run'))
groupE.add_argument(*anvio.A('debug'), **anvio.K('debug'))
groupE.add_argument(*anvio.A('skip-init-functions'), **anvio.K('skip-init-functions'))
groupF.add_argument(*anvio.A('ip-address'), **anvio.K('ip-address'))
groupF.add_argument(*anvio.A('port-number'), **anvio.K('port-number'))
groupF.add_argument(*anvio.A('read-only'), **anvio.K('read-only'))
groupF.add_argument(*anvio.A('server-only'), **anvio.K('server-only'))

args = parser.parse_args()

port = args.port_number
ip = args.ip_address

port = utils.get_available_port_num(start = port, ip=ip)

if not port:
    run.info_single('anvio failed to find a port number that is available :(', mc='red')
    sys.exit(-1)

unique_session_id = random.randint(0,9999999999)

try:
    r = refine.RefineBins(args)
    d = r.refine()
except ConfigError, e:
    print e
    sys.exit(-1)
except FilesNPathsError, e:
    print e
    sys.exit(-2)
except DictIOError, e:
    print e
    sys.exit(-3)
except SamplesError, e:
    print e
    sys.exit(-4)



#######################################################################################################################
# bottle callbacks start
#######################################################################################################################

def set_default_headers(response):
    response.set_header('Content-Type', 'application/json')
    response.set_header('Pragma', 'no-cache')
    response.set_header('Cache-Control', 'no-cache, no-store, max-age=0, must-revalidate')
    response.set_header('Expires', 'Thu, 01 Dec 1994 16:00:00 GMT')

@route('/')
def redirect_to_app():
    redirect('/app/index.html')

@route('/app/:filename#.*#')
def send_static(filename):
    set_default_headers(response)
    return static_file(filename, root=static_dir)

@route('/data/<name>')
def send_data(name):
    set_default_headers(response)
    if name == "init":
        return json.dumps( { "title": d.title,
                             "clusterings": (d.p_meta['default_clustering'], d.p_meta['clusterings']),
                             "views": (d.default_view, dict(zip(d.views.keys(), d.views.keys()))),
                             "contigLengths": dict([tuple((c, d.splits_basic_info[c]['length']),) for c in d.splits_basic_info]),
                             "defaultView": d.views[d.default_view],
                             "mode": "refine",
                             "readOnly": args.read_only,
                             "binPrefix": list(r.bins)[0] + "_" if len(r.bins) == 1 else "Refined_",
                             "sessionId": unique_session_id,
                             "samplesOrder": d.samples_order_dict,
                             "sampleInformation": d.samples_information_dict,
                             "sampleInformationDefaultLayerOrder": d.samples_information_default_layer_order,
                             "stateAutoload": d.state,
                             "noPing": False,
                             "inspectionAvailable": d.auxiliary_profile_data_available,
                             "sequencesAvailable": True if len(d.split_sequences) else False})
    elif name == "clusterings":
        return json.dumps((d.p_meta['default_clustering'], d.p_meta['clusterings']), )
    elif name == "views":
        available_views = dict(zip(d.views.keys(), d.views.keys()))
        return json.dumps((d.default_view, available_views), )
    elif name == "default_view":
        return json.dumps(d.views[d.default_view])
    elif name == "contig_lengths":
        split_lengths = dict([tuple((c, d.splits_basic_info[c]['length']),) for c in d.splits_basic_info])
        return json.dumps(split_lengths)
    elif name == "title":
        return json.dumps(d.title)
    elif name == "mode":
        return json.dumps("refine")
    elif name == "read_only":
        return json.dumps(args.read_only)
    elif name == "bin_prefix":
        if len(r.bins) == 1:
            return json.dumps(list(r.bins)[0] + "_")
        else:
            return json.dumps("Refined_")
    elif name == "session_id":
        return json.dumps(unique_session_id)
    elif name == "samples_order":
        return json.dumps(d.samples_order_dict)
    elif name == "samples_information":
        return json.dumps(d.samples_information_dict)
    elif name == "samples_information_default_layer_order":
        return json.dumps(d.samples_information_default_layer_order)
    elif name == "is_inspection_available":
        return json.dumps(d.auxiliary_profile_data_available)
    elif name == "is_inspection_available":
        return json.dumps(True if len(d.split_sequences) else False)

@route('/data/view/<view_id>')
def get_view_data(view_id):
    return routes.get_view_data(args, d, request, response, view_id)

@route('/tree/<tree_id>')
def get_tree(tree_id):
    return routes.get_tree(args, d, request, response, tree_id)

@route('/data/charts/<split_name>')
def charts(split_name):
    return routes.charts(d, split_name, show_outlier_SNVs = args.show_outlier_SNVs)

state_for_charts = {}

@route('/data/charts/set_state', method='POST')
def set_state():
    global state_for_charts
    state_for_charts = request.forms.get('state')

@route('/data/charts/get_state')
def get_parent_state():
    set_default_headers(response)
    return state_for_charts

@route('/data/gene/<gene_callers_id>')
def get_sequence_for_gene_call(gene_callers_id):
    return routes.get_sequence_for_gene_call(args, d, request, response, gene_callers_id)

@route('/data/contig/<split_name>')
def get_sequence_for_split(split_name):
    return routes.get_sequence_for_split(args, d, request, response, split_name)

@route('/store_refined_bins', method='POST')
def store_refined_bins():
    return routes.store_refined_bins(args, r, request, response)

@route('/data/completeness', method='POST')
def completeness():
    return routes.completeness(d, request)

@route('/state/autoload')
def state_autoload():
    return routes.state_autoload(d, response)

@route('/state/all')
def state_all():
    return routes.state_all(d, response)

@route('/state/get', method='POST')
def get_state():
    return routes.get_state(d, request, response)

@route('/state/save', method='POST')
def save_state():
    return routes.save_state(args, d, request, response)

#######################################################################################################################
# bottle callbacks end
#######################################################################################################################

# increase maximum size of form data to 100 MB
BaseRequest.MEMFILE_MAX = 1024 * 1024 * 100 

if args.dry_run:
    run.info_single('Dry run, eh? Bye!', 'red', nl_before = 1, nl_after=1)
    sys.exit()

try:
    server_process = Process(target=run_server, kwargs={'host': ip, 'port': port, 'quiet': True, 'server': 'cherrypy'})
    server_process.start()
    webbrowser.open_new("http://%s:%d" % (ip, port))
    run.info_single('When you are finished, press CTRL+C to terminate the server.', 'green', nl_before = 1, nl_after=1)
    server_process.join()
except KeyboardInterrupt:
    run.warning('The server is being terminated.', header='Please wait...')
    server_process.terminate()
    sys.exit(1)
