import json
import logging

from django.conf import settings
from django.views.decorators.http import require_http_methods

from staff.lib import requests
from staff.lib.decorators import responding_json, use_request_lang, available_for_external
from staff.lib.forms.errors import invalid_json_error, default_error
from staff.lib.forms.staff_form_grid import StaffFormGrid
from staff.person.models import Staff

from staff.person_profile.controllers import ssh_key as ctl
from staff.person_profile.forms.ssh_key import SSHKeyForm
from staff.person_profile.permissions.utils import observer_has_perm
from staff.person_profile.views.ssh_keys_view import ssh_keys as ssh_keys_view


logger = logging.getLogger('person_profile.edit_views.edit_ssh_keys_view')

FORM_NAME = 'ssh_keys'


@responding_json
@available_for_external
@require_http_methods(['GET', 'POST'])
@observer_has_perm('edit_ssh_keys')
@use_request_lang
def edit_ssh_keys(request, login):
    author_login = request.user.username

    if request.method == 'GET':
        # TODO login validation and error
        return {
            FORM_NAME: StaffFormGrid(
                SSHKeyForm, initial=ctl.get_initial(login)
            ).as_front_dict()
        }

    try:
        form_data = json.loads(request.body).get(FORM_NAME, [])
    except ValueError:
        logger.exception('Wrong JSON: %s', request.body)
        return invalid_json_error(request.body), 400

    person = Staff.objects.get(login=login)
    for item in form_data:
        item['person'] = person

    grid = StaffFormGrid(SSHKeyForm, data=form_data)
    if not grid.is_valid():
        return {'errors': {FORM_NAME: grid.errors()}}, 400

    try:
        ctl.update(login, grid.cleaned_data, author_login, request.real_user_ip)
    except ctl.SSHKeyError:
        return default_error(), 500

    return ssh_keys_view(request, login)


_cauth_session = requests.Session()


@responding_json
@available_for_external
@require_http_methods(['GET', 'POST'])
@observer_has_perm('edit_ssh_keys')
@use_request_lang
def send_verify_code(request, login):
    resp = _cauth_session.post(
        'https://{}/send_verification_code/'.format(settings.CAUTH_MASTER_HOST),
        data={'user_login': login},
    )
    return resp.json()
