# 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: treeupload/models.py
# class TreeSubmission(models.Model):
#     tree_file = models.FileField(
#         upload_to=os.path.join(settings.MEDIA_ROOT),
#     )
#     
#     tree_id = models.CharField(max_length=100)
#     
#     format_choices = sorted(bp._io.supported_formats.keys())
#     format_choices = [(x,x) for x in format_choices]
#     format = models.CharField(choices=format_choices, default='newick',
#                               max_length=20)
#     
#     uploaded_by = models.ForeignKey(User, related_name='uploaded_by')
#     upload_time = models.DateTimeField(auto_now_add=True)
# 
#     doi = models.CharField(max_length=100)
#     
#     def tree_file_name(self):
#         return os.path.split(self.tree_file.name)[1]
#         
#     def tree_file_size(self):
#         return filesizeformat(self.tree_file.size)
# 
# Path: treeupload/forms.py
# class TreeSubmissionForm(forms.ModelForm):
#     max_upload_size = MAX_UPLOAD_SIZE
# 
#     tree_id = forms.RegexField(
#         r'^[a-zA-Z][a-zA-Z0-9\_\-]*$', 
#         min_length=10, required=True,
#         error_message='Tree ID must be at least 10 characters, start with a letter, and contain only letters, numbers, dashes and underscores.'
#     )
#     
#     class Meta:
#         model = TreeSubmission
#         exclude = ['uploaded_by', 'upload_time']
#         
#     def clean(self, *args, **kwargs):
#         data = super(TreeSubmissionForm, self).clean(*args, **kwargs)
#         
#         try:
#             file = self.cleaned_data['tree_file']
#         except:
#             raise forms.ValidationError(_('No file selected.'))
#         
#         if file.size > self.max_upload_size:
#             raise forms.ValidationError(_('Please keep filesize under %s. Current filesize %s') % (filesizeformat(self.max_upload_size), filesizeformat(file._size)))
#             
#         return data


from django.shortcuts import render_to_response, redirect
from django.http import HttpResponse, HttpResponseRedirect
from django.core.context_processors import csrf
from django.core.urlresolvers import reverse
from django.template import RequestContext
from django.contrib.auth.decorators import login_required
from phylocommons.get_treestore import get_treestore, tree_id_from_uri, uri_from_tree_id
from treeupload.models import TreeSubmission
from treeupload.forms import TreeSubmissionForm
from cStringIO import StringIO
from phylocommons import settings
import Bio.Phylo as bp
    submission = TreeSubmission.objects.get(id=tree_id)
    file_path = submission.tree_file.path
    
    try:
        tree = bp.read(file_path, submission.format)
        s = StringIO()
        bp.write(tree, s, 'newick')
        text = '# SUCCESS\n%s' % s.getvalue()
    except Exception as e:
        text = '# ERROR: %s' % e
    
    response = HttpResponse(mimetype='text/plain')
    response.write(text)

    return response
    
    
@login_required
def upload_approve(request, tree_id):
    submission = TreeSubmission.objects.get(id=tree_id)
    tree_id = submission.tree_id
    file_path = submission.tree_file.path
    
    try:
        tree = bp.read(file_path, submission.format)
        with get_treestore() as treestore:
            treestore.add_trees(file_path, submission.format,
                                tree_uri=uri_from_tree_id(tree_id))
                                
            

# 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: treeupload/models.py
# class TreeSubmission(models.Model):
#     tree_file = models.FileField(
#         upload_to=os.path.join(settings.MEDIA_ROOT),
#     )
#     
#     tree_id = models.CharField(max_length=100)
#     
#     format_choices = sorted(bp._io.supported_formats.keys())
#     format_choices = [(x,x) for x in format_choices]
#     format = models.CharField(choices=format_choices, default='newick',
#                               max_length=20)
#     
#     uploaded_by = models.ForeignKey(User, related_name='uploaded_by')
#     upload_time = models.DateTimeField(auto_now_add=True)
# 
#     doi = models.CharField(max_length=100)
#     
#     def tree_file_name(self):
#         return os.path.split(self.tree_file.name)[1]
#         
#     def tree_file_size(self):
#         return filesizeformat(self.tree_file.size)
# 
# Path: treeupload/forms.py
# class TreeSubmissionForm(forms.ModelForm):
#     max_upload_size = MAX_UPLOAD_SIZE
# 
#     tree_id = forms.RegexField(
#         r'^[a-zA-Z][a-zA-Z0-9\_\-]*$', 
#         min_length=10, required=True,
#         error_message='Tree ID must be at least 10 characters, start with a letter, and contain only letters, numbers, dashes and underscores.'
#     )
#     
#     class Meta:
#         model = TreeSubmission
#         exclude = ['uploaded_by', 'upload_time']
#         
#     def clean(self, *args, **kwargs):
#         data = super(TreeSubmissionForm, self).clean(*args, **kwargs)
#         
#         try:
#             file = self.cleaned_data['tree_file']
#         except:
#             raise forms.ValidationError(_('No file selected.'))
#         
#         if file.size > self.max_upload_size:
#             raise forms.ValidationError(_('Please keep filesize under %s. Current filesize %s') % (filesizeformat(self.max_upload_size), filesizeformat(file._size)))
#             
#         return data


# Path: treeupload/views.py
from django.shortcuts import render_to_response, redirect
from django.http import HttpResponse, HttpResponseRedirect
from django.core.context_processors import csrf
from django.core.urlresolvers import reverse
from django.template import RequestContext
from django.contrib.auth.decorators import login_required
from phylocommons.get_treestore import get_treestore, tree_id_from_uri, uri_from_tree_id
from treeupload.models import TreeSubmission
from treeupload.forms import TreeSubmissionForm
from cStringIO import StringIO
from phylocommons import settings
import Bio.Phylo as bp

    submission = TreeSubmission.objects.get(id=tree_id)
    file_path = submission.tree_file.path
    
    try:
        tree = bp.read(file_path, submission.format)
        s = StringIO()
        bp.write(tree, s, 'newick')
        text = '# SUCCESS\n%s' % s.getvalue()
    except Exception as e:
        text = '# ERROR: %s' % e
    
    response = HttpResponse(mimetype='text/plain')
    response.write(text)

    return response
    
    
@login_required
def upload_approve(request, tree_id):
    submission = TreeSubmission.objects.get(id=tree_id)
    tree_id = submission.tree_id
    file_path = submission.tree_file.path
    
    try:
        tree = bp.read(file_path, submission.format)
        with get_treestore() as treestore:
            treestore.add_trees(file_path, submission.format,
                                tree_uri=uri_from_tree_id(tree_id))
                                
            

            text = 'Successfully uploaded <b>%s</b>.' % (uri_from_tree_id(tree_id))