from django.http import HttpResponse
from django.views.decorators.http import require_GET

from staff.lib.decorators import (
    responding_json,
    use_request_lang,
    available_for_external,
)
from staff.lib.forms.errors import default_error

from ..controllers import gpg_key as ctl
from ..permissions.utils import observer_has_perm


@available_for_external
@responding_json
@require_GET
@observer_has_perm('gpg_keys')
@use_request_lang
def download_gpg_key(request, login, id):
    try:
        key = ctl.get_key(login, id)
    except ctl.GPGKeyError:
        return default_error(), 500

    response = HttpResponse(
        key,
        content_type='application/octet-stream',
    )
    response['Content-Disposition'] = (
        'attachment; filename=gpg_%s_%s.txt' % (login, id)
    )
    return response
