from django.template import RequestContext, TemplateDoesNotExist
from django.template.loader import get_template, select_template
from django.views.decorators.clickjacking import xframe_options_exempt
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_GET, require_POST
from django.http import HttpResponse
from datetime import datetime
import pytz
import json
import os
import logging

from basecrowd.interface import CrowdRegistry
from basecrowd.tasks import gather_answer

logger = logging.getLogger('crowd_server')


@require_POST
@csrf_exempt
def create_task_group(request, crowd_name):
    """ See README.md for API. """

    # get the interface implementation from the crowd name.
    interface, model_spec = CrowdRegistry.get_registry_entry(crowd_name)

    # Response dictionaries
    correct_response = {'status': 'ok'}
    wrong_response = {'status': 'wrong'}

    # Parse information contained in the URL
    json_dict = request.POST.get('data')

    # Validate the format.
    if not interface.validate_create_request(json_dict):
        return HttpResponse(json.dumps(wrong_response))

    # Pull out important data fields
    json_dict = json.loads(json_dict)
    configuration = json_dict['configuration']
    group_id = json_dict['group_id']
    group_context = json.dumps(json_dict['group_context'])
    content = json_dict['content']
    point_identifiers = content.keys()

    # Create a new group for the tasks.
    current_group = model_spec.group_model(
        group_id=group_id,
        tasks_finished=0,
        callback_url=configuration['callback_url'],
        group_context=group_context,
        crowd_config=json.dumps(configuration.get(crowd_name, {})))

    # Call the group hook function, then save the new group to the database.
    interface.group_pre_save(current_group)
    current_group.save()

    # Create a task for each batch of points.
    for i in range(0, len(point_identifiers), configuration['task_batch_size']):

        # build the batch
        current_content = {}
        for j in range(i, i + configuration['task_batch_size']):

            if j >= len(point_identifiers):
                break
            current_content[point_identifiers[j]] = content[point_identifiers[j]]
        current_content = json.dumps(current_content)

        # Call the create task hook
        current_task_id = interface.create_task(configuration, current_content)

        # Build the task object
        current_task = model_spec.task_model(
            task_type=configuration['task_type'],
            data=current_content,
            create_time=pytz.utc.localize(datetime.now()),
            task_id=current_task_id,
            group=current_group,
            num_assignments=configuration['num_assignments'])

        # Call the pre-save hook, then save the task to the database.
        interface.task_pre_save(current_task)
        current_task.save()

    return HttpResponse(json.dumps(correct_response))


# Delete all tasks from the system.
def purge_tasks(request, crowd_name):
    interface, model_spec = CrowdRegistry.get_registry_entry(crowd_name)