# Path: phylocommons/get_treestore.py
# def get_treestore():
#     return Treestore(**settings.TREESTORE_KWARGS)
# 
# def tree_id_from_uri(uri):
#     return Treestore.id_from_uri(uri, base_uri=settings.TREE_URI)
# 
# def uri_from_tree_id(tree_id):
#     return Treestore.uri_from_id(tree_id, base_uri=settings.TREE_URI)
# 
# Path: treeview/views.py
# def download_plaintext(request, text=None, attachment=None, response=None):
#     if not response: response = HttpResponse(mimetype='text/plain')
#     if attachment:
#         response['Content-Disposition'] = 'attachment; filename=%s.%s.csv' % (site, taxon)
# 
#     if text: response.write(text)
# 
#     return response
# 
# Path: treequery/forms.py
# class QueryForm(forms.Form):
#     with get_treestore() as treestore:
#         taxa = forms.CharField(required=True,
#                                widget=forms.Textarea)
#         taxa.widget.attrs['class'] = 'stretch'
#         taxa.widget.attrs['placeholder'] = 'Enter a comma-separated list of taxa (e.g. Homo sapiens,Pan troglodytes,Pan paniscus,Gorilla gorilla,Pongo pygmaeus) to build a tree containing those taxa'
#         
#         format_choices = sorted(bp._io.supported_formats.keys()) + ['ascii']
#         format_choices = [('view', '(open in tree viewer)')] + [(x,x) for x in format_choices]
#         format = forms.ChoiceField(choices=format_choices,
#                                    initial=format_choices[0],
#                                    )
#         format.widget.attrs['class'] = 'stretch'
#                                    
#         prune = forms.BooleanField(required=False, initial=True)
#         
#         tree_list = [tree_id_from_uri(x) for x in treestore.list_trees()]
#         
#         tree_choices = [('', '(see all matching trees)'),
#                         ('best', '(choose the best match)')] + [(x,x) for x in tree_list]
#         tree = forms.ChoiceField(choices=tree_choices,
#                                  initial=tree_choices[0],
#                                  required=False)
#         tree.widget.attrs['class'] = 'combobox'
# 
#         tax_choices = [('', '(None)')] + [(x,x) for x in tree_list if x.endswith('_taxonomy')]
#         taxonomy = forms.ChoiceField(choices=tax_choices,
#                                      initial=settings.DEFAULT_TAXONOMY,
#                                      required=False)
#         taxonomy.widget.attrs['class'] = 'combobox'
#                                  
#         filter = forms.CharField(required=False)
#         filter.widget.attrs['class'] = 'stretch'


from django.shortcuts import render_to_response, redirect
from django.http import HttpResponse
from django.core.context_processors import csrf
from django.forms.util import ErrorList
from django.forms.forms import NON_FIELD_ERRORS
from django.template import RequestContext
from phylocommons.get_treestore import get_treestore, tree_id_from_uri, uri_from_tree_id
from treeview.views import download_plaintext
from treequery.forms import QueryForm
from cStringIO import StringIO
from phylocommons import settings
import Bio.Phylo as bp
import treeview.views
import urllib
import sys
            else:
                errors = form._errors.setdefault(NON_FIELD_ERRORS, ErrorList())
                if e:
                    errors.append('There was a problem with your query: %s' % e)
                else:
                    err_msg = "Your query didn't return a result. Try entering a new list of taxa"
                    if tree_uri: err_msg += ' or selecting a different tree'
                    err_msg += '.'
                    errors.append(err_msg)
            
            
        # show the query builder page
                
        params = {
                  'form': form,
                  'domain': settings.DOMAIN.rstrip('/'),
                  'tree_uri': settings.TREE_URI,
                  }
        params.update(csrf(request))
                
        return render_to_response(
            'query.html',
            params,
            context_instance=RequestContext(request)
        )

            

def query_disambiguate(request, matches, form_fields):
    if 'tree' in form_fields: del form_fields['tree']

# Path: phylocommons/get_treestore.py
# def get_treestore():
#     return Treestore(**settings.TREESTORE_KWARGS)
# 
# def tree_id_from_uri(uri):
#     return Treestore.id_from_uri(uri, base_uri=settings.TREE_URI)
# 
# def uri_from_tree_id(tree_id):
#     return Treestore.uri_from_id(tree_id, base_uri=settings.TREE_URI)
# 
# Path: treeview/views.py
# def download_plaintext(request, text=None, attachment=None, response=None):
#     if not response: response = HttpResponse(mimetype='text/plain')
#     if attachment:
#         response['Content-Disposition'] = 'attachment; filename=%s.%s.csv' % (site, taxon)
# 
#     if text: response.write(text)
# 
#     return response
# 
# Path: treequery/forms.py
# class QueryForm(forms.Form):
#     with get_treestore() as treestore:
#         taxa = forms.CharField(required=True,
#                                widget=forms.Textarea)
#         taxa.widget.attrs['class'] = 'stretch'
#         taxa.widget.attrs['placeholder'] = 'Enter a comma-separated list of taxa (e.g. Homo sapiens,Pan troglodytes,Pan paniscus,Gorilla gorilla,Pongo pygmaeus) to build a tree containing those taxa'
#         
#         format_choices = sorted(bp._io.supported_formats.keys()) + ['ascii']
#         format_choices = [('view', '(open in tree viewer)')] + [(x,x) for x in format_choices]
#         format = forms.ChoiceField(choices=format_choices,
#                                    initial=format_choices[0],
#                                    )
#         format.widget.attrs['class'] = 'stretch'
#                                    
#         prune = forms.BooleanField(required=False, initial=True)
#         
#         tree_list = [tree_id_from_uri(x) for x in treestore.list_trees()]
#         
#         tree_choices = [('', '(see all matching trees)'),
#                         ('best', '(choose the best match)')] + [(x,x) for x in tree_list]
#         tree = forms.ChoiceField(choices=tree_choices,
#                                  initial=tree_choices[0],
#                                  required=False)
#         tree.widget.attrs['class'] = 'combobox'
# 
#         tax_choices = [('', '(None)')] + [(x,x) for x in tree_list if x.endswith('_taxonomy')]
#         taxonomy = forms.ChoiceField(choices=tax_choices,
#                                      initial=settings.DEFAULT_TAXONOMY,
#                                      required=False)
#         taxonomy.widget.attrs['class'] = 'combobox'
#                                  
#         filter = forms.CharField(required=False)
#         filter.widget.attrs['class'] = 'stretch'


# Path: treequery/views.py
from django.shortcuts import render_to_response, redirect
from django.http import HttpResponse
from django.core.context_processors import csrf
from django.forms.util import ErrorList
from django.forms.forms import NON_FIELD_ERRORS
from django.template import RequestContext
from phylocommons.get_treestore import get_treestore, tree_id_from_uri, uri_from_tree_id
from treeview.views import download_plaintext
from treequery.forms import QueryForm
from cStringIO import StringIO
from phylocommons import settings
import Bio.Phylo as bp
import treeview.views
import urllib
import sys

            else:
                errors = form._errors.setdefault(NON_FIELD_ERRORS, ErrorList())
                if e:
                    errors.append('There was a problem with your query: %s' % e)
                else:
                    err_msg = "Your query didn't return a result. Try entering a new list of taxa"
                    if tree_uri: err_msg += ' or selecting a different tree'
                    err_msg += '.'
                    errors.append(err_msg)
            
            
        # show the query builder page
                
        params = {
                  'form': form,
                  'domain': settings.DOMAIN.rstrip('/'),
                  'tree_uri': settings.TREE_URI,
                  }
        params.update(csrf(request))
                
        return render_to_response(
            'query.html',
            params,
            context_instance=RequestContext(request)
        )

            

def query_disambiguate(request, matches, form_fields):
    if 'tree' in form_fields: del form_fields['tree']

    matches = [(tree_id_from_uri(m[0]), m[1]) for m in matches]