# -*- coding: utf-8 -*-

import http.client
import urllib.parse

from django.conf import settings


MESSAGE_BROKER_TOPICS = {
    'waitingroom': settings.CLIENT_NAME + '_waitingroom',
    'trainer': lambda x: settings.CLIENT_NAME + '_trainer_' + x,
    'trainee': lambda x: settings.CLIENT_NAME + '_trainee_' + x,
    'trainers': settings.CLIENT_NAME + '_trainers',
    'trainees': settings.CLIENT_NAME + '_trainees',
    'trainers_in_session': lambda x: settings.CLIENT_NAME + '_' + x[0] + '_trainers',
    'trainees_in_session': lambda x: settings.CLIENT_NAME + '_' + x[0] + '_trainees'
}


# FIXME: use async method (celery for example)
# FIXME: also rewrite this with requests?
def send_data_to_topic(msg, topic_name):
    params = urllib.parse.urlencode({topic_name: msg})
    headers = {'Content-type': 'application/x-www-form-urlencoded',
               'Accept': 'text/plain'}
    conn = http.client.HTTPConnection(
        settings.MESSAGE_BROKER_HTTP_HOST, settings.MESSAGE_BROKER_HTTP_PORT
    )
    conn.request('POST', settings.MESSAGE_BROKER_PUBLICATION_URL, params, headers)
    response = conn.getresponse()
    return response.status
