# vim: set fileencoding=utf-8 :
#
# Copyright (C) 2010-2012 Marnix H. Medema
# University of Groningen
# Department of Microbial Physiology / Groningen Bioinformatics Centre
#
# Copyright (C) 2011-2013 Kai Blin
# University of Tuebingen
# Interfaculty Institute of Microbiology and Infection Medicine
# Div. of Microbiology/Biotechnology
# 
# Copyright (C) 2017 Marnix Medema
# Wageningen University
# Bioinformatics Group
#
# 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

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

    return False

def generate_details_div(cluster, seq_record, options, js_domains, details=None):
    """Generate details div"""

    cluster_rec = utils.get_cluster_by_nr(seq_record, cluster['idx'])
    if cluster_rec is None:
        return details

    leader_peptides = _find_leader_peptides(cluster_rec, seq_record)
    core_peptides = _find_core_peptides(cluster_rec, seq_record)


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

        header = pq('<h3>')
        header.text('Detailed annotation')
        details.append(header)

    if len(core_peptides) == 0:
        details_text = pq('<div>')
        details_text.addClass('details-text')
        details_text.text('No core peptides found.')
        details.append(details_text)
        return details

    details_text = pq('<dl>')
    details_text.addClass('details-text')
    hrtag=pq('<hr>')
    header2 = pq('<h4>')
    header2.text('Sactipeptide(s)')
    details.append(header2)
    details.append(hrtag)

    
    i = 0
    for cp in core_peptides:
        leader = leader_peptides[i]
        leader_seq = _get_leader_peptide_sequence(leader)
        core_seq = _get_core_peptide_sequence(cp)
        rodeo_score = _get_core_peptide_rodeo_score(cp)
 
        dt = pq('<dt>')
        dt.text('%s leader / core peptide, putative sactipeptide' % (utils.get_gene_id(cp)))
        details_text.append(dt)

        dd = pq('<dd>')
        seq = "%s%s" % (leader_seq, core_seq)
        dd.html(seq)
        details_text.append(dd)
        i += 1

    details.append(details_text)

    return details

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')

    core_peptides = _find_core_peptides(cluster_rec, seq_record)
    if len(core_peptides) == 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 cp in core_peptides:
        dt = pq('<dt>')
        dt.text(utils.get_gene_id(cp))
        details_list.append(dt)
        dd = pq('<dd>')
        core_seq = _get_core_peptide_sequence(cp)
        rodeo_score = _get_core_peptide_rodeo_score(cp)
        dd.html('Putative sactipeptide<br>RODEO score: %0.2f<br>Core sequence, approximate: %r' %\
                (rodeo_score, core_seq))
        details_list.append(dd)
    details.append(details_list)
    sidepanel.append(details)

    
    
    cross_refs = pq("<div>")
    refs_header = pq('<h3>')
    refs_header.text('Database cross-links')
    cross_refs.append(refs_header)
    links = pq("<div>")
    links.addClass('prediction-text')

    a = pq("<a>")
    a.attr('href', 'http://bioinfo.lifl.fr/norine/form2.jsp')
    a.attr('target', '_new')
    a.text("Look up in NORINE database")
    links.append(a)
    cross_refs.append(links)
    sidepanel.append(cross_refs)

    return sidepanel

def _find_core_peptides(cluster, seq_record):
    """Find CDS_motifs containing sactipeptide core peptide annotations"""
    motifs = []

    for motif in utils.get_all_features_of_type(seq_record, 'CDS_motif'):
        if motif.location.start < cluster.location.start or \
           motif.location.end > cluster.location.end:
            continue

        if not motif.qualifiers.has_key('note'):
            continue

        if not 'core peptide' in motif.qualifiers['note']:
            continue

        if not 'sactipeptide' in motif.qualifiers['note']:
            continue
        
        motifs.append(motif)

    return motifs

def _find_leader_peptides(cluster, seq_record):
    """Find CDS_motifs containing  sactipeptide leader peptide annotations"""
    motifs = []
    for motif in utils.get_all_features_of_type(seq_record, 'CDS_motif'):
        if motif.location.start < cluster.location.start or \
           motif.location.end > cluster.location.end:
            continue

        if not motif.qualifiers.has_key('note'):
            continue

        if not 'leader peptide' in motif.qualifiers['note']:
            continue
        
        if not 'sactipeptide' in motif.qualifiers['note']:
            continue
        
        motifs.append(motif)

    return motifs

def _get_leader_peptide_sequence(motif):
    """Get AA sequence of a core peptide motif"""
    for note in motif.qualifiers['note']:
        if not note.startswith('predicted leader seq:'):
            continue
        return note.split(':')[-1].strip()

def _get_core_peptide_sequence(motif):
    """Get AA sequence of a core peptide motif"""
    for note in motif.qualifiers['note']:
        if not note.startswith('predicted core seq:'):
            continue
        return note.split(':')[-1].strip()

def _get_core_peptide_score(motif):
    """Get the score of the core peptide prediction"""
    for note in motif.qualifiers['note']:
        if not note.startswith('score:'):
            continue
        return float(note.split(':')[-1].strip())

def _get_core_peptide_rodeo_score(motif):
    """Get the score of the core peptide prediction"""
    for note in motif.qualifiers['note']:
        if not note.startswith('RODEO score:'):
            continue
        return int(note.split(':')[-1].strip())



