import logging

from django.conf import settings
from django.http import HttpResponse, HttpResponseForbidden, HttpResponseBadRequest, HttpResponseNotFound
from django.views.decorators.csrf import csrf_exempt

from staff.lib.decorators import responding_json, auth_by_tvm_only, available_for_external

from staff.verification.forms import LoginVerificationForm
from staff.verification.export import export
from staff.verification.objects import ExternalLoginCtl, can_manage_ext_login


logger = logging.getLogger(__name__)


@csrf_exempt
@available_for_external
def extlogin_activate(request):
    # Проверяем токен, так как эти ручки доверяют только нужному приложению
    app = request.client_application
    if not app or app.id != settings.OAUTH_ID:
        return HttpResponseNotFound('Unknown app ' + (app.id if app else ''))

    ext_uid, ext_login, int_login = [
        request.POST[f] for f in ('ext_uid', 'ext_login', 'int_login')
    ]

    # Проверяем int логин
    form = LoginVerificationForm({'target': int_login})
    if not form.is_valid():
        logger.warning('Activate with unknown internal login %s', int_login)
        return HttpResponseBadRequest('Unknown internal login %s' % int_login)
    target = form.cleaned_data['target']
    observer = request.user.get_profile()

    if not can_manage_ext_login(target, observer):
        return HttpResponseForbidden(
            'No rights to activate. %s -- %s' % (int_login, ext_login)
        )

    logger.info(
        'Activating external login %s for internal login %s with %s external uid',
        ext_login,
        target.login,
        ext_uid,
    )
    ext_login_ctl = ExternalLoginCtl(target=target, observer=observer)
    ext_login_ctl.activate(ext_uid=ext_uid, ext_login=ext_login)

    return HttpResponse('Everything is OK')


@csrf_exempt
@available_for_external
def extlogin_deactivate(request):
    app = request.client_application
    if not app or app.id != settings.OAUTH_ID:
        return HttpResponseNotFound('Unknown app' + (app.id if app else ''))

    int_login = request.POST['int_login']

    form = LoginVerificationForm({'target': int_login})
    if not form.is_valid():
        return HttpResponseBadRequest('Unknown internal login %s' % int_login)
    target = form.cleaned_data['target']
    observer = request.user.get_profile()

    if not can_manage_ext_login(target, observer):
        return HttpResponseForbidden('No rights to deactivate. %s' % int_login)

    ExternalLoginCtl(target=target, observer=observer).deactivate()

    return HttpResponse('Everything is OK')


@auth_by_tvm_only(['yadisk', 'new_yadisk'])
@responding_json
def export_login_links(request):
    internal_logins = request.GET.getlist('internal_login')
    internal_uids = request.GET.getlist('internal_uid')
    return export(internal_logins, internal_uids)
