from json import loads

from BaseLib.BaseView import BaseView
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

    def get(self):
        self.context['configs'] = Config.objects.filter(project=self.request.user.selected_project, stage=self.stage).order_by('name')
        self.context['error'] = 'error' in self.request.GET

    def post_create_config(self):
        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()
        return '/configs/?stage=' + config.stage

    def post_save(self):
        data = self.request.POST['data']
        try:
            data = loads(data)
        except:
            return '/configs?error=config_is_not_json'
        config = Config.objects.get(id=self.request.POST['config'])
        config.data = data
        config.save()
        return '/configs/?stage=' + config.stage
