import json

from django.http import HttpResponse
from django.shortcuts import render_to_response
from django.template import RequestContext

from pymongo import Connection

from slides.views import slides_db

connection = Connection()
workflow_db = connection.ime.workflow
workflow_db.create_index('name', unique=True)

def add_workflow(request):
    workflows = list(workflow_db.find())
    for workflow in workflows:
        del workflow['_id']

    context = {
        'workflows': json.dumps(workflows),
        'slides': list(slides_db.find()),
    }
    return render_to_response('workflow.html', context_instance=RequestContext(request, context))

def ajax(request):
    action = request.GET.get('action', '')

    if action == 'create_workflow':
        workflow_db.insert({'name': request.GET['name'], 'slides': []})

    elif action == 'add_slide':
        workflow = workflow_db.find_one({'name': request.GET['name']})
        workflow['slides'].append(request.GET['slide_id'])
        workflow_db.save(workflow)

    elif action == 'rearrange':
        request.GET['positions']
        
        

    elif action == 'delete':
        # TODO: delete slide
        pass

    return HttpResponse('ok')

def play(request, id):
    workflow = workflow_db.find_one({'name': id})

    slides = list(slides_db.find({'name': {"$in": workflow['slides']}}))
    for slide in slides:
        del slide['_id']

    context = {
        'slides': slides,
    }
    return render_to_response('play.html', context_instance=RequestContext(request, context))
