from BaseLib.BaseView import BaseView
from experiments.models import Experiment


class ExperimentsView(BaseView):
    required_login = True
    endpoint = ''
    view_file = 'experiments.html'

    def pre_handle(self):
        if 'stage' not in self.request.GET or self.request.GET['stage'] not in ['development', 'production']:
            return '/experiments/?stage=production'
        self.stage = self.request.GET['stage']
        self.context['stage'] = self.stage

    def get(self):
        self.context['experiments'] = Experiment.objects.filter(project=self.request.user.selected_project,
                                                        stage=self.stage).order_by('name')

    def post_create(self):
        Experiment.objects.create(project=self.request.user.selected_project, stage=self.stage, name=self.request.POST['name'])
        return '/experiments/?stage=' + self.stage

    def post_delete(self):
        Experiment.objects.get(id=self.request.POST['experiment_id']).delete()
        return '/experiments/?stage=' + self.stage
    def post_change(self):
        exp = Experiment.objects.get(id=self.request.POST['experiment_id'])
        exp.enabled = 'enabled' in self.request.POST
        condition = self.request.POST['condition_select']
        if condition == 'Другое (только для техлидов)':
            exp.condition = self.request.POST['condition']
        elif condition == 'Никому':
            exp.condition = 'False'
        elif condition == 'Только админам':
            exp.condition = 'user.is_superuser'
        elif condition == 'Только сотрудникам':
            exp.condition = 'user.is_staff'
        else:
            exp.condition = 'True'
        exp.save()
        return '/experiments/?stage=' + self.stage