from django.views.decorators.http import require_http_methods
from django.views.decorators.csrf import csrf_exempt

from staff.jabber import get_status_bulk, add_to_jabber
from staff.lib.decorators import responding_json
from staff.lib.forms.errors import general_error, DEFAULT_GENERAL_ERROR

import logging
logger = logging.getLogger(__name__)

ADD_YOURSELF_ERROR = 'cannot_add_yourself'
ALREADY_ADDED_ERROR = 'already_added'


@require_http_methods(['GET', 'POST'])
@responding_json
def status(request):
    req_data = request.GET or request.POST
    logins = req_data.getlist('u')

    if not logins:
        return {}

    statuses = get_status_bulk(logins)

    return {
        login: {'status': statuses.get(login)}
        for login in logins
    }


@require_http_methods(['GET', 'POST'])
@csrf_exempt
@responding_json
def add(request):
    req_data = request.GET or request.POST
    roster_owner_login = request.user.username
    logins = [login for login in req_data.getlist('u') if login != roster_owner_login]

    if not logins:
        return {roster_owner_login: ADD_YOURSELF_ERROR}

    try:
        adding_result = add_to_jabber(roster_owner_login, logins)
        for login in adding_result.keys():
            if 'Contact already added under the group.' in adding_result[login]:
                adding_result[login] = ALREADY_ADDED_ERROR
        return adding_result
    except Exception:
        logger.exception('')
        return general_error(DEFAULT_GENERAL_ERROR), 500
