from json import loads

from django.http import HttpResponse, JsonResponse

from BaseLib.BaseView import BaseView
from BaseLib.configurator import *
from Platform import settings
from schemas.models import Schema


# Create your views here.


class SchemasView(BaseView):
    required_login = True
    endpoint = ''
    view_file = 'schemas.html'

    def pre_handle(self):
        self.context['schemas'] = Schema.objects.filter(project=self.request.user.selected_project)

    def post_create_schema(self):
        Schema.objects.create(project=self.request.user.selected_project, name=self.request.POST['name'])
        return '/schemas'

    def post_delete(self):
        Schema.objects.get(id=self.request.POST['schema']).delete()
        return '/schemas'


    def post_save(self):
        schema = Schema.objects.get(id=self.request.POST['schema'])
        schema.data = self.request.POST['data']
        schema.save()
        return '/schemas'


def get_schemas(request):
    project = request.GET.get('project')
    if project is None:
        return HttpResponse('', status=400)
    data = {
        schema.name: schema.data
        for schema in Schema.objects.filter(project__name=project)
    }
    return JsonResponse(data, safe=False)
