from django.contrib.auth.decorators import login_required, user_passes_test
from rest_framework.decorators import api_view
from rest_framework.response import Response

from console.serializers import CelerySerializer
from core.decorators import log_url
from storage.tasks import dump_db


@log_url
@login_required
@user_passes_test(lambda u: u.is_superuser)
@api_view(('GET',))
def download_db_snapshot(request):
    """ Downloads fixture to restore current DB state, for test and dev purposes only
     request->models allow to control which tables would be downloaded, for example 'auth,console.userinfo """
    dump_models = request.GET.get('models', tuple())
    if dump_models:
        dump_models = dump_models.split(',')

    res = dump_db.apply_async(args=(request.user.pk, dump_models))
    serializer = CelerySerializer(data={'task_id': res.id})
    serializer.is_valid()

    return Response(serializer.data)
