from json import loads

from django.http import HttpResponse, JsonResponse

from BaseLib.BaseView import BaseView
from BaseLib.configurator import *
from Platform import settings
from configs.models import Config


# Create your views here.


class ConfigsView(BaseView):
    required_login = True
    endpoint = ''
    view_file = 'configs.html'

    def pre_handle(self):
        if 'stage' not in self.request.GET or self.request.GET['stage'] not in ['development', 'production']:
            return '/configs/?stage=production'
        self.stage = self.request.GET['stage']
        self.context['stage'] = self.stage
        # self.context['configs'] = Config.objects.filter(project=self.request.user.selected_project,
        #                                                 stage=self.stage).order_by('name')
        self.context['configs'] = get_configs(self.request.user.selected_project.name, self.stage)

    def post_create_config(self):
        create_config(self.request.user.selected_project.name, self.stage, self.request.POST['name'])
        # Config.objects.create(name=self.request.POST['name'], project=self.request.user.selected_project, stage=self.stage)
        return '/configs/?stage=' + self.stage

    def post_delete(self):
        # config = Config.objects.get(id=self.request.POST['config'])
        # config.delete()
        delete_config(self.request.POST['config'])
        return '/configs/?stage=' + self.stage

    def post_save(self):
        data = self.request.POST['data']
        # config = Config.objects.get(id=self.request.POST['config'])
        try:
            data = loads(data)
        except:
            self.context['incorrect_config'] = self.request.POST['config']
            self.context['incorrect_data'] = data
            self.context['error'] = True
            return
        update_config(self.request.POST['config'], data)
        # config.data = data
        # config.save()
        return '/configs/?stage=' + self.stage


def get_config(request):
    if request.headers.get("X-Security-Token") != settings.PLATFORM_SECURITY_TOKEN:
        return HttpResponse('', status=403)
    project = request.GET.get('project')
    stage = request.GET.get('stage')
    name = request.GET.get('name')
    if project is None or stage is None or name is None:
        return HttpResponse('', status=400)
    config = Config.objects.filter(stage=stage, project__name=project, name=name).first()
    if config is None:
        return HttpResponse('', status=404)
    return JsonResponse(config.data, safe=False)
