# 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
            }
        
        if request.method == 'POST':
            form = QueryForm(request.POST)
            if form.is_valid():
                url = '/query/?' + urllib.urlencode(form.cleaned_data.items())
                if len(url) < 200: return redirect(url)
                params.update(form.cleaned_data)
                submitted_query = True
            else:
                submitted_query = False
            
        elif request.method == 'GET' and 'taxa' in request.GET:
            submitted_query = True
            taxa = request.GET.get('taxa')
            params.update(request.GET.dict())
            if 'prune' in request.GET: params['prune'] = params['prune'] == 'True'
            form = QueryForm(initial=request.GET.dict())
            form.full_clean()
            
        else:
            submitted_query = False
            form = QueryForm(initial=request.GET.dict())
        

        best_match = params['tree'] == 'best'
        
        if submitted_query:
            if best_match: tree_uri = None
            else: tree_uri = uri_from_tree_id(params['tree']) if params['tree'] else None

# 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

            }
        
        if request.method == 'POST':
            form = QueryForm(request.POST)
            if form.is_valid():
                url = '/query/?' + urllib.urlencode(form.cleaned_data.items())
                if len(url) < 200: return redirect(url)
                params.update(form.cleaned_data)
                submitted_query = True
            else:
                submitted_query = False
            
        elif request.method == 'GET' and 'taxa' in request.GET:
            submitted_query = True
            taxa = request.GET.get('taxa')
            params.update(request.GET.dict())
            if 'prune' in request.GET: params['prune'] = params['prune'] == 'True'
            form = QueryForm(initial=request.GET.dict())
            form.full_clean()
            
        else:
            submitted_query = False
            form = QueryForm(initial=request.GET.dict())
        

        best_match = params['tree'] == 'best'
        
        if submitted_query:
            if best_match: tree_uri = None
            else: tree_uri = uri_from_tree_id(params['tree']) if params['tree'] else None

            taxonomy = uri_from_tree_id(params['taxonomy']) if params['taxonomy'] else None