# Path: inmembrane/helpers.py
# def log_stderr(s, width=76, comment=True):
#     """
#     Wrapper for all stderr out. Allows future customization.
#     """
#     if LOG_SILENT:
#         return
#     if s and s[-1] != "\n":
#         s += "\n"
#     if not s.startswith("#"):
#         s = "# " + s
#     sys.stderr.write(s)
# 
# def parse_fasta_header(header):
#     """
#     Parses a FASTA format header (with our without the initial '>') and returns a
#     tuple of sequence id and sequence name/description.
# 
#     If NCBI SeqID format (gi|gi-number|gb|accession etc, is detected
#     the first id in the list is used as the canonical id (see see
#     http://www.ncbi.nlm.nih.gov/books/NBK21097/#A631 ).
#     """
#     if header[0] == '>':
#         header = header[1:]
#     tokens = header.split('|')
#     # check to see if we have an NCBI-style header
#     if header.find("|") != -1 and len(tokens[0]) <= 3:
#         # "gi|ginumber|gb|accession bla bla" becomes "gi|ginumber"
#         seqid = "%s|%s" % (tokens[0], tokens[1].split()[0])
#         name = tokens[-1:][0].strip()
#     # otherwise just split on spaces & hope for the best
#     else:
#         tokens = header.split()
#         seqid = tokens[0]
#         name = header[0:-1].strip()
# 
#     return seqid, name
# 
# def dict_get(this_dict, prop):
#     """
#     Useful helper function to get values from dicts. Takes in
#     the possibility that the key may not exist, and in that
#     case returns False. Makes it easier to write code to avoid
#     handling the case of missing keys.
#     """
#     if prop not in this_dict:
#         return False
#     return this_dict[prop]


import sys, os, time, StringIO
import requests
from BeautifulSoup import BeautifulSoup
from inmembrane.helpers import log_stderr, parse_fasta_header, dict_get

def annotate(params, proteins, \
             url="http://rbf.bioinfo.tw/" +
                 "~sachen/OMPpredict/" +
                 "TMBETADISC-RBF-Content.html", force=False):
    """
    Interfaces with the TMBETADISC-RBF web service at
    (http://rbf.bioinfo.tw/~sachen/OMPpredict/TMBETADISC-RBF.php)
    to predict if protein sequence is likely to be an outer membrane beta-barrel.

    Note that the default URL we use it different to the regular form used
    by web browsers, since we need to bypass some AJAX fun.
    """
    # TODO: automatically split large sets into multiple jobs
    #       since TMBETADISC seems to not like more than take
    #       ~5000 seqs at a time
    if len(proteins) >= 5000:
        log_stderr(
            "# ERROR: TMBETADISC-RBF(web): tends to fail with > ~5000 sequences.")
        return

    # set the user-agent so web services can block us if they want ... :/
    python_version = sys.version.split()[0]
    # TODO: Set User-Agent header for requests
    # agent("Python-urllib/%s (requests; inmembrane)" % python_version)

    outfn = 'tmbetadisc-rbf.out'
    log_stderr("# TMBETADISC-RBF(web) %s > %s" % (params['fasta'], outfn))

    if not force and os.path.isfile(outfn):

# Path: inmembrane/helpers.py
# def log_stderr(s, width=76, comment=True):
#     """
#     Wrapper for all stderr out. Allows future customization.
#     """
#     if LOG_SILENT:
#         return
#     if s and s[-1] != "\n":
#         s += "\n"
#     if not s.startswith("#"):
#         s = "# " + s
#     sys.stderr.write(s)
# 
# def parse_fasta_header(header):
#     """
#     Parses a FASTA format header (with our without the initial '>') and returns a
#     tuple of sequence id and sequence name/description.
# 
#     If NCBI SeqID format (gi|gi-number|gb|accession etc, is detected
#     the first id in the list is used as the canonical id (see see
#     http://www.ncbi.nlm.nih.gov/books/NBK21097/#A631 ).
#     """
#     if header[0] == '>':
#         header = header[1:]
#     tokens = header.split('|')
#     # check to see if we have an NCBI-style header
#     if header.find("|") != -1 and len(tokens[0]) <= 3:
#         # "gi|ginumber|gb|accession bla bla" becomes "gi|ginumber"
#         seqid = "%s|%s" % (tokens[0], tokens[1].split()[0])
#         name = tokens[-1:][0].strip()
#     # otherwise just split on spaces & hope for the best
#     else:
#         tokens = header.split()
#         seqid = tokens[0]
#         name = header[0:-1].strip()
# 
#     return seqid, name
# 
# def dict_get(this_dict, prop):
#     """
#     Useful helper function to get values from dicts. Takes in
#     the possibility that the key may not exist, and in that
#     case returns False. Makes it easier to write code to avoid
#     handling the case of missing keys.
#     """
#     if prop not in this_dict:
#         return False
#     return this_dict[prop]


# Path: inmembrane/plugins/tmbetadisc_rbf_web.py
import sys, os, time, StringIO
import requests
from BeautifulSoup import BeautifulSoup
from inmembrane.helpers import log_stderr, parse_fasta_header, dict_get


def annotate(params, proteins, \
             url="http://rbf.bioinfo.tw/" +
                 "~sachen/OMPpredict/" +
                 "TMBETADISC-RBF-Content.html", force=False):
    """
    Interfaces with the TMBETADISC-RBF web service at
    (http://rbf.bioinfo.tw/~sachen/OMPpredict/TMBETADISC-RBF.php)
    to predict if protein sequence is likely to be an outer membrane beta-barrel.

    Note that the default URL we use it different to the regular form used
    by web browsers, since we need to bypass some AJAX fun.
    """
    # TODO: automatically split large sets into multiple jobs
    #       since TMBETADISC seems to not like more than take
    #       ~5000 seqs at a time
    if len(proteins) >= 5000:
        log_stderr(
            "# ERROR: TMBETADISC-RBF(web): tends to fail with > ~5000 sequences.")
        return

    # set the user-agent so web services can block us if they want ... :/
    python_version = sys.version.split()[0]
    # TODO: Set User-Agent header for requests
    # agent("Python-urllib/%s (requests; inmembrane)" % python_version)

    outfn = 'tmbetadisc-rbf.out'
    log_stderr("# TMBETADISC-RBF(web) %s > %s" % (params['fasta'], outfn))

    if not force and os.path.isfile(outfn):

        log_stderr("# -> skipped: %s already exists" % outfn)