from django.http import HttpResponse, JsonResponse

from Platform import settings
from configs.models import Config
from experiments.models import Experiment
from web.models import CustomUser


def fetch(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')
    if project is None or stage is None:
        return HttpResponse('', status=400)
    configs = Config.objects.filter(stage=stage, project__name=project)
    experiments = Experiment.objects.filter(stage=stage, project__name=project)
    platform_staff = {
        'vk_id': [],
        'yandex_id': [],
        'telegram_id': [],
        'email': [],
    }
    for user in CustomUser.objects.filter(is_active=True):
        if user.vk_id:
            platform_staff['vk_id'].append(user.vk_id)
        if user.yandex_id:
            platform_staff['yandex_id'].append(user.yandex_id)
        if user.telegram_id:
            platform_staff['telegram_id'].append(user.telegram_id)
        if user.email:
            platform_staff['email'].append(user.email)
    return JsonResponse(
        data={
            'configs': {config.name: config.data for config in configs},
            'experiments': {experiment.name: {'enabled': experiment.enabled, 'condition': experiment.condition} for experiment in experiments},
            'platform_staff': platform_staff,
        },
        safe=False,
    )
