#!/usr/bin/env python
'''Functions that interact with external tools/services
'''
from __future__ import absolute_import, print_function, division
from peyotl.nexson_syntax import get_ot_study_info_from_nexml, \
                                 DEFAULT_NEXSON_VERSION, \
                                 BY_ID_HONEY_BADGERFISH, \
                                 convert_nexson_format, \
                                 sort_arbitrarily_ordered_nexson
from peyotl.nexson_syntax.helper import _simplify_all_meta_by_id_del

def _get_treebase_url(treebase_id):
    # Use TreeBASE API to fetch NeXML, then pass it as a string
    # to _import_nexson_from_nexml()

    # EXAMPLE: Here's Phylografter's fetch URL for study 15515 as 'nexml' (versus 'nexus'):
    #   http://purl.org/phylo/treebase/phylows/study/TB2:S15515?format=nexml
    # ... which redirects to:
    #   http://treebase.org/treebase-web/phylows/study/TB2:S15515?format=nexml
    # ... which redirects to:
    #   http://treebase.org/treebase-web/search/downloadAStudy.html?id=15515&format=nexml
    #
    # Since our download follows redirects, let's respect the PhyloWS API on treebase.org
    url_format = 'http://treebase.org/treebase-web/phylows/study/TB2:S{t:d}?format=nexml'
    return url_format.format(t=treebase_id)


def get_ot_study_info_from_treebase_nexml(src=None,
                                          nexml_content=None,
                                          encoding=u'utf8',
                                          nexson_syntax_version=DEFAULT_NEXSON_VERSION,
                                          merge_blocks=True,
                                          sort_arbitrary=False):
    '''Normalize treebase-specific metadata into the locations where
    open tree of life software that expects it.

    See get_ot_study_info_from_nexml for the explanation of the src,
    nexml_content, encoding, and nexson_syntax_version arguments
    If merge_blocks is True then peyotl.manip.merge_otus_and_trees