from requests import get, put, post, delete
from json import dumps


URL_CONFIGS = 'http://configurator/api/v1/configs'
URL_EXPERIMENTS = 'http://configurator/api/v1/experiments'


def get_configs(project, stage):
    response = get(URL_CONFIGS, params={'project': project, 'stage': stage})
    if response.status_code != 200:
        return []
    data = response.json()
    for config in data:
        config['value_pretty'] = dumps(config['value'], indent=4, ensure_ascii=False)
    return data


def create_config(project, stage, name):
    post(URL_CONFIGS, json={'project': project, 'stage': stage, 'name': name})


def update_config(id, value):
    put(URL_CONFIGS, json={'id': id, 'value': value})


def delete_config(id):
    delete(URL_CONFIGS, json={'id': id})


def get_experiments(project, stage):
    response = get(URL_EXPERIMENTS, params={'project': project, 'stage': stage})
    if response.status_code != 200:
        return []
    data = response.json()
    for exp in data:
        if exp['condition'] == 'False':
            exp['exp_type'] = 0
        elif exp['condition'] == 'user.is_superuser':
            exp['exp_type'] = 1
        elif exp['condition'] == 'user.platform_staff':
            exp['exp_type'] = 2
        elif exp['condition'] == 'True':
            exp['exp_type'] = 3
        else:
            exp['exp_type'] = 4
    return data

def create_experiment(project, stage, name):
    post(URL_EXPERIMENTS, json={'project': project, 'stage': stage, 'name': name})


def update_experiment(id, enabled, condition):
    put(URL_EXPERIMENTS, json={'id': id, 'enabled': enabled, 'condition': condition})


def delete_experiment(id):
    delete(URL_CONFIGS, json={'id': id})
