# vim: set fileencoding=utf-8 :
#
# Copyright (C) 2016 Marnix H. Medema
# Wageningen University, Bioinformatics Group
#
# Copyright (C) 2016 Marc Chevrette
# University of Wisconsin, Madison; Currie Lab
#
# License: GNU Affero General Public License v3 or later
# A copy of GNU AGPL v3 should have been included in this software package in LICENSE.txt.

from pyquery import PyQuery as pq
from antismash import utils
from specific_analysis import find_terpene_synthases

def will_handle(product):
    if product.find('terpene') > -1:
        return True
    return False

def generate_sidepanel(cluster, seq_record, options, sidepanel=None):
    """Generate sidepanel div"""
    cluster_rec = utils.get_cluster_by_nr(seq_record, cluster['idx'])
    if cluster_rec is None:
        return sidepanel

    if sidepanel is None:
        sidepanel = pq('<div>')
        sidepanel.addClass('sidepanel')

    terpene_synthases = find_terpene_synthases([cluster_rec], seq_record)
    if len(terpene_synthases) == 0:
        return sidepanel

    details = pq('<div>')
    details.addClass('more-details')
    details_header = pq('<h3>')
    details_header.text('Prediction details')
    details.append(details_header)
    details_list = pq('<dl>')
    details_list.addClass('prediction-text')

    for tps in terpene_synthases:
        dt = pq('<dt>')
        dt.text(utils.get_gene_id(tps))
        details_list.append(dt)
        dd = pq('<dd>')
        cp = _get_cyclization_pattern(tps)
        nn = _get_nearest_neighbour(tps)
        name, acc, pid = _get_best_blast_hit(tps)
        if acc != None:
            dd.html('Cyclization pattern predicted: %s<br>'\
                'Nearest neighbour: %s<br>'\
                'Best known BLAST hit: %s (%s, %s %%ID)<br>' % (cp, nn, name, acc, pid))
        else:
            dd.html('Cyclization pattern predicted: %s<br>'\
                'Nearest neighbour: %s<br>'\
                'Best known BLAST hit: %s<br>' % (cp, nn, name))
        details_list.append(dd)
    details.append(details_list)
    sidepanel.append(details)

    return sidepanel


def _get_cyclization_pattern(motif):
    """Get predicted cyclization pattern"""
    pattern = None
    for note in motif.qualifiers['note']:
        if not note.startswith('Cyclization pattern:'):
            continue
        pattern = note.split(': ')[-1].strip()
        break
    if pattern is not None and pattern != 'no_confident_result':
        return pattern
    return "no confident result"


def _get_best_blast_hit(motif):
    """Get predicted cyclization pattern"""
    for note in motif.qualifiers['note']:
        if not note.startswith('Best known BLAST hit:'):
            continue
        contents = note.split(': ')[-1]
        name = contents.partition(" (")[0]
        if name == "No BLAST hit":
            return name, None, None
        acc = contents.partition(" (")[2].partition(",")[0]
        pid = contents.partition(" (")[2].partition(", ")[2].partition(" %")[0]
        return name, acc, pid

def _get_nearest_neighbour(motif):
    """Get neareast neighbour name and %ID"""
    for note in motif.qualifiers['note']:
        if not note.startswith('Nearest neighbour:'):
            continue
        nn = note.split(': ')[-1]
        return nn
