<commit_before># -*- coding: utf-8 -*-
# Create your views here.
from django.http import HttpResponse, HttpResponseRedirect, HttpResponseNotFound
from django.shortcuts import render_to_response
from django.template.response import TemplateResponse
from django.core.exceptions import ObjectDoesNotExist
from django.views.decorators.csrf import csrf_protect
from django.contrib.auth import REDIRECT_FIELD_NAME
from django.template import RequestContext
from django.db import transaction
from django.http import JsonResponse

import logging
import xml.etree.ElementTree as ET
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User
from backends import AuthAlreadyAssociated, google_query_me, facebook_query_me
from django.db.models import Avg, Count

from activitytree.models import Course,ActivityTree,UserLearningActivity, LearningActivity, ULA_Event, FacebookSession,LearningActivityRating,AuthorLearningActivity
from activitytree.interaction_handler import SimpleSequencing
from activitytree.interaction_handler import get_nav

from activitytree.activities import activities, multi_device_activities
from activitytree.models import FacebookSession, GoogleSession,UserProfile
from mongo_activities import Activity
from django.db import IntegrityError
import urllib
import urlparse

from eval_code.RedisCola import Cola, Task
import json
from django.conf import settings
from courses import  create_course_from_json, get_activity_tree

import redis

ip_couch = "http://127.0.0.1:5984"
redis_service = redis.Redis("127.0.0.1")
logger = logging.getLogger(__name__)

def welcome(request):
    courses = Course.objects.all()

    if request.user.is_authenticated() and request.user != 'AnonymousUser' :
         return render_to_response('activitytree/welcome.html',
            {'courses':courses
                #, 'plus_scope':plus_scope,'plus_id':plus_id
            },
                context_instance=RequestContext(request))
    else:
        return render_to_response('activitytree/welcome.html',
            {'user_name':None,'courses':courses
                #,'plus_scope':plus_scope,'plus_id':plus_id
                 },
                context_instance=RequestContext(request))

def my_courses(request):



    if request.user.is_authenticated() and request.user != 'AnonymousUser' :


         courses = LearningActivity.objects.filter(authorlearningactivity__user = request.user )

         return render_to_response('activitytree/welcome.html',
            {'courses':courses
                #, 'plus_scope':plus_scope,'plus_id':plus_id
            },
                context_instance=RequestContext(request))
    else:
        return HttpResponseRedirect('/login/?next=%s' % request.path)




def course(request,course_id):
    print request.POST
    return render_to_response('activitytree/course_builder.html',
            {'user_name':None,'courses':None
                #,'plus_scope':plus_scope,'plus_id':plus_id
                 },
                context_instance=RequestContext(request))




def dashboard(request,path_id):
    if request.user.is_authenticated():
        if request.method == 'GET':

            s = SimpleSequencing()

            # First, the requested_activity  exists??
            # Gets the Learning Activity object from uri
            requested_activity = None
            try:
                requested_activity = UserLearningActivity.objects.get(learning_activity__id = path_id ,user = request.user )
            except (ObjectDoesNotExist, IndexError) as e:
                requested_activity = None


            if not requested_activity:
                return HttpResponseNotFound('<h1>Activity not found</h1>')

            # Gets the root of the User Learning Activity
            root = UserLearningActivity.objects.get(learning_activity_id = path_id ,user = request.user )

                # Exits last activity, and sets requested activity as current
                # if choice_exit consider complete


            _XML = get_nav(root)
            #Escape for javascript
            XML=ET.tostring(_XML,'utf-8').replace('"', r'\"')        #navegation_tree = s.nav_to_html(nav)

            return render_to_response('activitytree/dashboard.html', {'XML_NAV':XML,
                                    'children': requested_activity.get_children(),
                                    'uri':requested_activity.learning_activity.uri,
                                    'root':requested_activity.learning_activity.get_root().uri,
                                    'root':requested_activity.learning_activity.get_root().uri
                                                                    },
                                      context_instance=RequestContext(request))


def path_activity(request,path_id, uri):
    learning_activity = None
    try:
        learning_activity = LearningActivity.objects.get(pk=path_id)
    except ObjectDoesNotExist:
        return HttpResponseNotFound('<h1>Learning Activity not found</h1>')

    if request.user.is_authenticated():
        root=None
        s = SimpleSequencing()
        requested_activity = None

        if request.method == 'GET':
            try:
                requested_activity = UserLearningActivity.objects.get(learning_activity__id = path_id ,user = request.user )
            except (ObjectDoesNotExist, IndexError) as e:
                requested_activity = None


            # The requested_activity was NOT FOUND
            if not requested_activity: # The requested_activity was not found
            # Maybe a
            # 'start' REQUEST?
            #    if 'nav' in request.GET and request.GET['nav'] == 'start':
                if learning_activity and learning_activity.root is None:
                    s.assignActivityTree(request.user,learning_activity)
                    requested_activity = UserLearningActivity.objects.get(learning_activity__id = path_id ,user = request.user)
                    _set_current(request,requested_activity, requested_activity, s)
                    return HttpResponseRedirect( '/%s%s'% (path_id , uri))
                #If is not a root learning activity then sorry, not found
                else:
                    return HttpResponseNotFound('<h1>Activity not found</h1>')
            #Else NOT FOUND
                #else:
                #    return HttpResponseNotFound('<h1>Activity not found</h1>')

            # We have a valid requested_activity, lets handle OTHER NAVIGATION REQUEST

            #Get root of activity tree
            root = UserLearningActivity.objects.filter(learning_activity = requested_activity.learning_activity.get_root(),
                                                       user = request.user )[0]
            # 'continue' REQUEST?
            if requested_activity.is_root() and 'nav' in request.GET and request.GET['nav'] == 'continue':
                current_activity = s.get_current(requested_activity)
                if current_activity:
                    requested_activity = current_activity
                    return HttpResponseRedirect(  '/%s%s'% (requested_activity.learning_activity.id, requested_activity.learning_activity.uri))
                else:
                    _set_current(request,requested_activity, root, s, progress_status=None)
            #Else is a
            # 'choice' REQUEST
            else:
                _set_current(request,requested_activity, root, s)

        if request.method == 'POST' and 'nav_event' in request.POST:
            #Get root of activity tree
            root = None
            try:
                root = UserLearningActivity.objects.get(learning_activity__id = path_id ,user = request.user )
            except (ObjectDoesNotExist, IndexError) as e:
                root = None


            if not root or not root.is_root():
                return HttpResponseNotFound('<h1>Activity not found</h1>')

            current_activity = s.get_current(root)


            if current_activity.learning_activity.choice_exit:
                progress_status='completed'
            else:
                progress_status = None

            # 'next' REQUEST
            if request.POST['nav_event'] == 'next':
                # Go TO NEXT ACTIVITY
                s.exit( current_activity, progress_status = progress_status)
                next_uri = s.get_next(root, current_activity)

            # 'prev' REQUEST
            elif request.POST['nav_event'] == 'prev':
                # Go TO PREV ACTIVITY
                s.exit( current_activity, progress_status = progress_status)
                next_uri = s.get_prev(root, current_activity)

            #No more activities ?
            if next_uri is None:

                return HttpResponseRedirect( '/%s%s'% (root.learning_activity.id , root.learning_activity.uri))

            else:
                next_activity = UserLearningActivity.objects.get(learning_activity__id = next_uri ,user = request.user )
                return HttpResponseRedirect( '/%s%s'% (next_activity.learning_activity.id,next_activity.learning_activity.uri))


        _XML = get_nav(root)
        #Escape for javascript
        XML=ET.tostring(_XML,'utf-8').replace('"', r'\"')

        breadcrumbs = s.get_current_path(requested_activity)

        rating_totals = LearningActivityRating.objects.filter(learning_activity__uri=requested_activity.learning_activity.uri).aggregate(Count('rating'), Avg('rating'))

        activity_content = Activity.get(requested_activity.learning_activity.uri)


        if activity_content and 'content' in activity_content:
            content = activity_content['content']
        else:
            content = ""

        update_pool(requested_activity.learning_activity.uri)

        if (requested_activity.learning_activity.uri).split('/')[2] =='video':
            return render_to_response('activitytree/video.html',

                                  {'XML_NAV':XML,
                                   'uri':requested_activity.learning_activity.uri,
                                   'uri_id':requested_activity.learning_activity.id,
                                   'video':activity_content,
                                   'breadcrumbs':breadcrumbs,
                                   'root':requested_activity.learning_activity.get_root().uri,
                                   'root_id':'/%s'% requested_activity.learning_activity.get_root().id,
                                    'rating_totals':rating_totals },
                                    context_instance=RequestContext(request))

        elif requested_activity.learning_activity.is_container:

            return render_to_response('activitytree/container.html',

                                  {
                                   'XML_NAV':XML,
                                   'children': requested_activity.get_children(),
                                   'uri':requested_activity.learning_activity.uri,
                                   'uri_id':'/%s'% requested_activity.learning_activity.id,
                                   'content':content,
                                   'root':requested_activity.learning_activity.get_root().uri,
                                   'root_id':'/%s'% requested_activity.learning_activity.get_root().id,
                                   'breadcrumbs':breadcrumbs},
                                    context_instance=RequestContext(request))
        else:
            return render_to_response('activitytree/activity.html',

                                  {'XML_NAV':XML,
                                   'uri':requested_activity.learning_activity.uri,
                                   'uri_id':'/%s'% requested_activity.learning_activity.id,
                                   'content':content,
                                   'root':requested_activity.learning_activity.get_root().uri,
                                   'root_id':'/%s'% requested_activity.learning_activity.get_root().id,
                                   'breadcrumbs':breadcrumbs,
                                    'rating_totals':rating_totals},
                                    context_instance=RequestContext(request))

    else:
        return HttpResponseRedirect('/login/?next=%s' % request.path)



def activity(request, uri=None):
    if request.method == 'GET':

        # Check if public, all public for now
        if False:
            return HttpResponseRedirect('/login/?next=%s' % request.path)

        activity_content = Activity.get('/%s' % uri)

        if activity_content and 'content' in activity_content:
            content = activity_content['content']
        else:
            content = ""


        if (uri).split('/')[1] =='video':

            return render_to_response('activitytree/video.html',

                                  {'XML_NAV':None,
                                   'uri':uri,
                                   'video':activity_content,
                                   'breadcrumbs':None },
                                    context_instance=RequestContext(request))


        else:
            return render_to_response('activitytree/activity.html',

                                  {'XML_NAV':None,
                                   'uri':uri,
                                   'content':content,
                                   'breadcrumbs':None,
                                   },
                                    context_instance=RequestContext(request))


        # Do something for anonymous users.    

def path_test(request,path_id, uri):

    if request.user.is_authenticated():
        s = SimpleSequencing()
        try:
            requested_activity = UserLearningActivity.objects.get(learning_activity__id = path_id ,user = request.user )
        except ObjectDoesNotExist as e:
            return HttpResponseNotFound('<h1>Learning Activity not found</h1>')

        root = None

        try:
            root = UserLearningActivity.objects.get(learning_activity = requested_activity.learning_activity.get_root() ,user = request.user )
        except (ObjectDoesNotExist, IndexError) as e:
                return HttpResponseNotFound('<h1>Path not found</h1>')

        feedback = None
        attempts_left = requested_activity.learning_activity.attempt_limit-requested_activity.num_attempts
        if request.method == 'GET':
            # Exits last activity, and sets requested activity as current
            # if choice_exit consider complete
            _set_current(request,requested_activity, root, s, progress_status=None)

        elif request.method == 'POST':
            if 'check' in request.POST and attempts_left :

                    #quiz = activities[requested_activity.learning_activity.uri]
                    quiz = Activity.get(requested_activity.learning_activity.uri)

                    feedback = _check_quiz(request.POST, quiz)
                    # Updates the current Learning Activity
                    objective_measure = float(feedback['total_correct'])/len(quiz['questions'])*100
                    if feedback['total_correct'] >= quiz['satisfied_at_least']:
                        progress_status='completed'
                    else:
                        progress_status='incomplete'

                    s.update(requested_activity, progress_status = progress_status, attempt=True)
                    attempts_left-=1


       # Gets the current navegation tree as HTML

        _XML = get_nav(root)
        #Escape for javascript
        XML=ET.tostring(_XML,'utf-8').replace('"', r'\"')        #navegation_tree = s.nav_to_html(nav)
        rating_totals = LearningActivityRating.objects.filter(learning_activity__uri=requested_activity.learning_activity.uri).aggregate(Count('rating'), Avg('rating'))

        breadcrumbs = s.get_current_path(requested_activity)



        test = Activity.get(requested_activity.learning_activity.uri)


        if feedback:
            for q in test['questions']:
                if q['id'] in feedback:
                    q['feedback'] = feedback[q['id']]
                    if q['interaction']  in ['choiceInteraction','simpleChoice']:
                        q['feedback_options'] = zip(q['options'], feedback[q['id']]['user_answer'], feedback[q['id']]['checked'])

        return render_to_response('activitytree/'+(requested_activity.learning_activity.uri).split('/')[1]+'.html',
                                  {'XML_NAV':XML,
                                   'uri':requested_activity.learning_activity.uri,
                                   'content':test,
                                   'feedback':feedback,
                                   'breadcrumbs':breadcrumbs,
                                   'uri_id':'/%s'% requested_activity.learning_activity.id,


                                   'attempt_limit':requested_activity.learning_activity.attempt_limit,
                                  'num_attempts': requested_activity.num_attempts,
                                   'attempts_left':attempts_left ,
                                   'root_id':'/%s'% requested_activity.learning_activity.get_root().id,

                                    'root':requested_activity.learning_activity.get_root().uri},

                                    context_instance=RequestContext(request))
    else:

        return HttpResponseRedirect('/login/?next=%s' % request.path)
        # Do something for anonymous users.



def path_program(request,path_id, uri):
    if request.user.is_authenticated():
        s = SimpleSequencing()
        try:
            requested_activity = UserLearningActivity.objects.get(learning_activity__id = path_id ,user = request.user )
        except ObjectDoesNotExist as e:
            return HttpResponseNotFound('<h1>Learning Activity not found</h1>')
        root = None
        try:
            root = UserLearningActivity.objects.get(learning_activity = requested_activity.learning_activity.get_root() ,user = request.user )
        except (ObjectDoesNotExist, IndexError) as e:
                return HttpResponseNotFound('<h1>Path not found</h1>')

        if request.method == 'GET':
            # Exits last activity, and sets requested activity as current
            # if choice_exit consider complete
            _set_current(request,requested_activity, root, s)

        # Gets the current navegation tree as XML
        _XML = get_nav(root)
        #Escape for javascript
        XML=ET.tostring(_XML,'utf-8').replace('"', r'\"')

        breadcrumbs = s.get_current_path(requested_activity)
        program_quiz = Activity.get(requested_activity.learning_activity.uri)
        rating_totals = LearningActivityRating.objects.filter(learning_activity__uri=requested_activity.learning_activity.uri).aggregate(Count('rating'), Avg('rating'))



        if program_quiz['lang'] == 'javascript':
            template = 'activitytree/programjs.html'
        else:
            template = 'activitytree/program.html'

        return render_to_response(template, {'program_quiz':Activity.get(requested_activity.learning_activity.uri),
                                                                    'activity_uri':requested_activity.learning_activity.uri,
                                                                    'uri_id':'%s'% requested_activity.learning_activity.id,
                                                                    'uri':requested_activity.learning_activity.uri,
                                                                    'breadcrumbs':breadcrumbs,
                                                                    'root':requested_activity.learning_activity.get_root().uri,
                                                                    'root_id':'/%s'% requested_activity.learning_activity.get_root().id,
                                                                    'XML_NAV':XML, 'rating_totals':rating_totals
                                                                    },
                                      context_instance=RequestContext(request))

    else:
        return HttpResponseRedirect('/login/?next=%s' % request.path)

@transaction.atomic
def program(request, uri):

    program_quiz = Activity.get(request.path)

    if program_quiz:

        if program_quiz['lang'] == 'javascript':
            template = 'activitytree/programjs.html'
        else:
            template = 'activitytree/program.html'

        return render_to_response(template, {           'program_quiz':program_quiz,
                                                        'activity_uri':request.path,
                                                        'breadcrumbs':None,
                                                        'root':None,
                                                        'XML_NAV':None
                                                        },
                          context_instance=RequestContext(request))
    else:

        return HttpResponseNotFound('<h1>Activity not found</h1>')

@csrf_protect
def execute_queue(request):
    logger.error("VIEW execute_queue")
    if request.method == 'POST':
        rpc=json.loads(request.body)

        logger.error("POST:"+rpc["params"][0]+rpc["method"])


        code = rpc["params"][0]
        activity_uri = rpc["method"]
        program_test = Activity.get(activity_uri)
        unit_test = program_test['unit_test']
        server = Cola(program_test['lang'])

        task = {"id": None, "method": "exec", "params": {"code": code, "test": unit_test}}
        logger.error(task)
        task_id = server.enqueue(**task)
        logger.error(task_id)

        if request.user.is_authenticated() and 'id' in rpc:
            ula = None
            try:<commit_msg>logger<commit_after># -*- coding: utf-8 -*-
# Create your views here.
from django.http import HttpResponse, HttpResponseRedirect, HttpResponseNotFound
from django.shortcuts import render_to_response
from django.template.response import TemplateResponse
from django.core.exceptions import ObjectDoesNotExist
from django.views.decorators.csrf import csrf_protect
from django.contrib.auth import REDIRECT_FIELD_NAME
from django.template import RequestContext
from django.db import transaction
from django.http import JsonResponse

import logging
import xml.etree.ElementTree as ET
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User
from backends import AuthAlreadyAssociated, google_query_me, facebook_query_me
from django.db.models import Avg, Count

from activitytree.models import Course,ActivityTree,UserLearningActivity, LearningActivity, ULA_Event, FacebookSession,LearningActivityRating,AuthorLearningActivity
from activitytree.interaction_handler import SimpleSequencing
from activitytree.interaction_handler import get_nav

from activitytree.activities import activities, multi_device_activities
from activitytree.models import FacebookSession, GoogleSession,UserProfile
from mongo_activities import Activity
from django.db import IntegrityError
import urllib
import urlparse

from eval_code.RedisCola import Cola, Task
import json
from django.conf import settings
from courses import  create_course_from_json, get_activity_tree

import redis

ip_couch = "http://127.0.0.1:5984"
redis_service = redis.Redis("127.0.0.1")
logger = logging.getLogger(__name__)

def welcome(request):
    courses = Course.objects.all()

    if request.user.is_authenticated() and request.user != 'AnonymousUser' :
         return render_to_response('activitytree/welcome.html',
            {'courses':courses
                #, 'plus_scope':plus_scope,'plus_id':plus_id
            },
                context_instance=RequestContext(request))
    else:
        return render_to_response('activitytree/welcome.html',
            {'user_name':None,'courses':courses
                #,'plus_scope':plus_scope,'plus_id':plus_id
                 },
                context_instance=RequestContext(request))

def my_courses(request):



    if request.user.is_authenticated() and request.user != 'AnonymousUser' :


         courses = LearningActivity.objects.filter(authorlearningactivity__user = request.user )

         return render_to_response('activitytree/welcome.html',
            {'courses':courses
                #, 'plus_scope':plus_scope,'plus_id':plus_id
            },
                context_instance=RequestContext(request))
    else:
        return HttpResponseRedirect('/login/?next=%s' % request.path)




def course(request,course_id):
    print request.POST
    return render_to_response('activitytree/course_builder.html',
            {'user_name':None,'courses':None
                #,'plus_scope':plus_scope,'plus_id':plus_id
                 },
                context_instance=RequestContext(request))




def dashboard(request,path_id):
    if request.user.is_authenticated():
        if request.method == 'GET':

            s = SimpleSequencing()

            # First, the requested_activity  exists??
            # Gets the Learning Activity object from uri
            requested_activity = None
            try:
                requested_activity = UserLearningActivity.objects.get(learning_activity__id = path_id ,user = request.user )
            except (ObjectDoesNotExist, IndexError) as e:
                requested_activity = None


            if not requested_activity:
                return HttpResponseNotFound('<h1>Activity not found</h1>')

            # Gets the root of the User Learning Activity
            root = UserLearningActivity.objects.get(learning_activity_id = path_id ,user = request.user )

                # Exits last activity, and sets requested activity as current
                # if choice_exit consider complete


            _XML = get_nav(root)
            #Escape for javascript
            XML=ET.tostring(_XML,'utf-8').replace('"', r'\"')        #navegation_tree = s.nav_to_html(nav)

            return render_to_response('activitytree/dashboard.html', {'XML_NAV':XML,
                                    'children': requested_activity.get_children(),
                                    'uri':requested_activity.learning_activity.uri,
                                    'root':requested_activity.learning_activity.get_root().uri,
                                    'root':requested_activity.learning_activity.get_root().uri
                                                                    },
                                      context_instance=RequestContext(request))


def path_activity(request,path_id, uri):
    learning_activity = None
    try:
        learning_activity = LearningActivity.objects.get(pk=path_id)
    except ObjectDoesNotExist:
        return HttpResponseNotFound('<h1>Learning Activity not found</h1>')

    if request.user.is_authenticated():
        root=None
        s = SimpleSequencing()
        requested_activity = None

        if request.method == 'GET':
            try:
                requested_activity = UserLearningActivity.objects.get(learning_activity__id = path_id ,user = request.user )
            except (ObjectDoesNotExist, IndexError) as e:
                requested_activity = None


            # The requested_activity was NOT FOUND
            if not requested_activity: # The requested_activity was not found
            # Maybe a
            # 'start' REQUEST?
            #    if 'nav' in request.GET and request.GET['nav'] == 'start':
                if learning_activity and learning_activity.root is None:
                    s.assignActivityTree(request.user,learning_activity)
                    requested_activity = UserLearningActivity.objects.get(learning_activity__id = path_id ,user = request.user)
                    _set_current(request,requested_activity, requested_activity, s)
                    return HttpResponseRedirect( '/%s%s'% (path_id , uri))
                #If is not a root learning activity then sorry, not found
                else:
                    return HttpResponseNotFound('<h1>Activity not found</h1>')
            #Else NOT FOUND
                #else:
                #    return HttpResponseNotFound('<h1>Activity not found</h1>')

            # We have a valid requested_activity, lets handle OTHER NAVIGATION REQUEST

            #Get root of activity tree
            root = UserLearningActivity.objects.filter(learning_activity = requested_activity.learning_activity.get_root(),
                                                       user = request.user )[0]
            # 'continue' REQUEST?
            if requested_activity.is_root() and 'nav' in request.GET and request.GET['nav'] == 'continue':
                current_activity = s.get_current(requested_activity)
                if current_activity:
                    requested_activity = current_activity
                    return HttpResponseRedirect(  '/%s%s'% (requested_activity.learning_activity.id, requested_activity.learning_activity.uri))
                else:
                    _set_current(request,requested_activity, root, s, progress_status=None)
            #Else is a
            # 'choice' REQUEST
            else:
                _set_current(request,requested_activity, root, s)

        if request.method == 'POST' and 'nav_event' in request.POST:
            #Get root of activity tree
            root = None
            try:
                root = UserLearningActivity.objects.get(learning_activity__id = path_id ,user = request.user )
            except (ObjectDoesNotExist, IndexError) as e:
                root = None


            if not root or not root.is_root():
                return HttpResponseNotFound('<h1>Activity not found</h1>')

            current_activity = s.get_current(root)


            if current_activity.learning_activity.choice_exit:
                progress_status='completed'
            else:
                progress_status = None

            # 'next' REQUEST
            if request.POST['nav_event'] == 'next':
                # Go TO NEXT ACTIVITY
                s.exit( current_activity, progress_status = progress_status)
                next_uri = s.get_next(root, current_activity)

            # 'prev' REQUEST
            elif request.POST['nav_event'] == 'prev':
                # Go TO PREV ACTIVITY
                s.exit( current_activity, progress_status = progress_status)
                next_uri = s.get_prev(root, current_activity)

            #No more activities ?
            if next_uri is None:

                return HttpResponseRedirect( '/%s%s'% (root.learning_activity.id , root.learning_activity.uri))

            else:
                next_activity = UserLearningActivity.objects.get(learning_activity__id = next_uri ,user = request.user )
                return HttpResponseRedirect( '/%s%s'% (next_activity.learning_activity.id,next_activity.learning_activity.uri))


        _XML = get_nav(root)
        #Escape for javascript
        XML=ET.tostring(_XML,'utf-8').replace('"', r'\"')

        breadcrumbs = s.get_current_path(requested_activity)

        rating_totals = LearningActivityRating.objects.filter(learning_activity__uri=requested_activity.learning_activity.uri).aggregate(Count('rating'), Avg('rating'))

        activity_content = Activity.get(requested_activity.learning_activity.uri)


        if activity_content and 'content' in activity_content:
            content = activity_content['content']
        else:
            content = ""

        update_pool(requested_activity.learning_activity.uri)

        if (requested_activity.learning_activity.uri).split('/')[2] =='video':
            return render_to_response('activitytree/video.html',

                                  {'XML_NAV':XML,
                                   'uri':requested_activity.learning_activity.uri,
                                   'uri_id':requested_activity.learning_activity.id,
                                   'video':activity_content,
                                   'breadcrumbs':breadcrumbs,
                                   'root':requested_activity.learning_activity.get_root().uri,
                                   'root_id':'/%s'% requested_activity.learning_activity.get_root().id,
                                    'rating_totals':rating_totals },
                                    context_instance=RequestContext(request))

        elif requested_activity.learning_activity.is_container:

            return render_to_response('activitytree/container.html',

                                  {
                                   'XML_NAV':XML,
                                   'children': requested_activity.get_children(),
                                   'uri':requested_activity.learning_activity.uri,
                                   'uri_id':'/%s'% requested_activity.learning_activity.id,
                                   'content':content,
                                   'root':requested_activity.learning_activity.get_root().uri,
                                   'root_id':'/%s'% requested_activity.learning_activity.get_root().id,
                                   'breadcrumbs':breadcrumbs},
                                    context_instance=RequestContext(request))
        else:
            return render_to_response('activitytree/activity.html',

                                  {'XML_NAV':XML,
                                   'uri':requested_activity.learning_activity.uri,
                                   'uri_id':'/%s'% requested_activity.learning_activity.id,
                                   'content':content,
                                   'root':requested_activity.learning_activity.get_root().uri,
                                   'root_id':'/%s'% requested_activity.learning_activity.get_root().id,
                                   'breadcrumbs':breadcrumbs,
                                    'rating_totals':rating_totals},
                                    context_instance=RequestContext(request))

    else:
        return HttpResponseRedirect('/login/?next=%s' % request.path)



def activity(request, uri=None):
    if request.method == 'GET':

        # Check if public, all public for now
        if False:
            return HttpResponseRedirect('/login/?next=%s' % request.path)

        activity_content = Activity.get('/%s' % uri)

        if activity_content and 'content' in activity_content:
            content = activity_content['content']
        else:
            content = ""


        if (uri).split('/')[1] =='video':

            return render_to_response('activitytree/video.html',

                                  {'XML_NAV':None,
                                   'uri':uri,
                                   'video':activity_content,
                                   'breadcrumbs':None },
                                    context_instance=RequestContext(request))


        else:
            return render_to_response('activitytree/activity.html',

                                  {'XML_NAV':None,
                                   'uri':uri,
                                   'content':content,
                                   'breadcrumbs':None,
                                   },
                                    context_instance=RequestContext(request))


        # Do something for anonymous users.    

def path_test(request,path_id, uri):

    if request.user.is_authenticated():
        s = SimpleSequencing()
        try:
            requested_activity = UserLearningActivity.objects.get(learning_activity__id = path_id ,user = request.user )
        except ObjectDoesNotExist as e:
            return HttpResponseNotFound('<h1>Learning Activity not found</h1>')

        root = None

        try:
            root = UserLearningActivity.objects.get(learning_activity = requested_activity.learning_activity.get_root() ,user = request.user )
        except (ObjectDoesNotExist, IndexError) as e:
                return HttpResponseNotFound('<h1>Path not found</h1>')

        feedback = None
        attempts_left = requested_activity.learning_activity.attempt_limit-requested_activity.num_attempts
        if request.method == 'GET':
            # Exits last activity, and sets requested activity as current
            # if choice_exit consider complete
            _set_current(request,requested_activity, root, s, progress_status=None)

        elif request.method == 'POST':
            if 'check' in request.POST and attempts_left :

                    #quiz = activities[requested_activity.learning_activity.uri]
                    quiz = Activity.get(requested_activity.learning_activity.uri)

                    feedback = _check_quiz(request.POST, quiz)
                    # Updates the current Learning Activity
                    objective_measure = float(feedback['total_correct'])/len(quiz['questions'])*100
                    if feedback['total_correct'] >= quiz['satisfied_at_least']:
                        progress_status='completed'
                    else:
                        progress_status='incomplete'

                    s.update(requested_activity, progress_status = progress_status, attempt=True)
                    attempts_left-=1


       # Gets the current navegation tree as HTML

        _XML = get_nav(root)
        #Escape for javascript
        XML=ET.tostring(_XML,'utf-8').replace('"', r'\"')        #navegation_tree = s.nav_to_html(nav)
        rating_totals = LearningActivityRating.objects.filter(learning_activity__uri=requested_activity.learning_activity.uri).aggregate(Count('rating'), Avg('rating'))

        breadcrumbs = s.get_current_path(requested_activity)



        test = Activity.get(requested_activity.learning_activity.uri)


        if feedback:
            for q in test['questions']:
                if q['id'] in feedback:
                    q['feedback'] = feedback[q['id']]
                    if q['interaction']  in ['choiceInteraction','simpleChoice']:
                        q['feedback_options'] = zip(q['options'], feedback[q['id']]['user_answer'], feedback[q['id']]['checked'])

        return render_to_response('activitytree/'+(requested_activity.learning_activity.uri).split('/')[1]+'.html',
                                  {'XML_NAV':XML,
                                   'uri':requested_activity.learning_activity.uri,
                                   'content':test,
                                   'feedback':feedback,
                                   'breadcrumbs':breadcrumbs,
                                   'uri_id':'/%s'% requested_activity.learning_activity.id,


                                   'attempt_limit':requested_activity.learning_activity.attempt_limit,
                                  'num_attempts': requested_activity.num_attempts,
                                   'attempts_left':attempts_left ,
                                   'root_id':'/%s'% requested_activity.learning_activity.get_root().id,

                                    'root':requested_activity.learning_activity.get_root().uri},

                                    context_instance=RequestContext(request))
    else:

        return HttpResponseRedirect('/login/?next=%s' % request.path)
        # Do something for anonymous users.



def path_program(request,path_id, uri):
    if request.user.is_authenticated():
        s = SimpleSequencing()
        try:
            requested_activity = UserLearningActivity.objects.get(learning_activity__id = path_id ,user = request.user )
        except ObjectDoesNotExist as e:
            return HttpResponseNotFound('<h1>Learning Activity not found</h1>')
        root = None
        try:
            root = UserLearningActivity.objects.get(learning_activity = requested_activity.learning_activity.get_root() ,user = request.user )
        except (ObjectDoesNotExist, IndexError) as e:
                return HttpResponseNotFound('<h1>Path not found</h1>')

        if request.method == 'GET':
            # Exits last activity, and sets requested activity as current
            # if choice_exit consider complete
            _set_current(request,requested_activity, root, s)

        # Gets the current navegation tree as XML
        _XML = get_nav(root)
        #Escape for javascript
        XML=ET.tostring(_XML,'utf-8').replace('"', r'\"')

        breadcrumbs = s.get_current_path(requested_activity)
        program_quiz = Activity.get(requested_activity.learning_activity.uri)
        rating_totals = LearningActivityRating.objects.filter(learning_activity__uri=requested_activity.learning_activity.uri).aggregate(Count('rating'), Avg('rating'))



        if program_quiz['lang'] == 'javascript':
            template = 'activitytree/programjs.html'
        else:
            template = 'activitytree/program.html'

        return render_to_response(template, {'program_quiz':Activity.get(requested_activity.learning_activity.uri),
                                                                    'activity_uri':requested_activity.learning_activity.uri,
                                                                    'uri_id':'%s'% requested_activity.learning_activity.id,
                                                                    'uri':requested_activity.learning_activity.uri,
                                                                    'breadcrumbs':breadcrumbs,
                                                                    'root':requested_activity.learning_activity.get_root().uri,
                                                                    'root_id':'/%s'% requested_activity.learning_activity.get_root().id,
                                                                    'XML_NAV':XML, 'rating_totals':rating_totals
                                                                    },
                                      context_instance=RequestContext(request))

    else:
        return HttpResponseRedirect('/login/?next=%s' % request.path)

@transaction.atomic
def program(request, uri):

    program_quiz = Activity.get(request.path)

    if program_quiz:

        if program_quiz['lang'] == 'javascript':
            template = 'activitytree/programjs.html'
        else:
            template = 'activitytree/program.html'

        return render_to_response(template, {           'program_quiz':program_quiz,
                                                        'activity_uri':request.path,
                                                        'breadcrumbs':None,
                                                        'root':None,
                                                        'XML_NAV':None
                                                        },
                          context_instance=RequestContext(request))
    else:

        return HttpResponseNotFound('<h1>Activity not found</h1>')

@csrf_protect
def execute_queue(request):
    logger.error("VIEW execute_queue")
    if request.method == 'POST':
        rpc=json.loads(request.body)
        import os


        logger.error("REDIS:"+os.environ['REDIS_HOST'])


        code = rpc["params"][0]
        activity_uri = rpc["method"]
        program_test = Activity.get(activity_uri)
        unit_test = program_test['unit_test']
        server = Cola(program_test['lang'])

        task = {"id": None, "method": "exec", "params": {"code": code, "test": unit_test}}
        logger.error(task)
        task_id = server.enqueue(**task)
        logger.error(task_id)

        if request.user.is_authenticated() and 'id' in rpc:
            ula = None
            try:
{'fraction_non_alphanumeric': 0.09002849002849003, 'fraction_numerical': 0.002301994301994302, 'mean_word_length': 1.8750409540659196, 'pattern_counts': {'":': 10, '<': 43, '<?xml version=': 0, '>': 45, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 2}, 'pii_count': 4, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 176, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '1163641', 'n_tokens_mistral': 11143, 'n_tokens_neox': 10512, 'n_words': 2009}