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


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


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 []
    return response.json()


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})
