import io
import yaml

from django.http import HttpResponse
from django.views import View
from rest_framework import status
from rest_framework.response import Response

from intranet.femida.src.api.core.views import BaseView
from intranet.femida.src.api.users.serializers import AuthUserSerializer
from intranet.femida.src.permissions.models import SERVICE_PERMISSIONS
from intranet.femida.src.utils.authdata import AuthDataMixin
from intranet.femida.src.utils.csp import CSPMixin


class MetaView(BaseView):

    def get(self, request, *args, **kwargs):
        return Response(
            data={
                'user': AuthUserSerializer(request.user).data
            },
            status=status.HTTP_200_OK,
        )


class ServicePermissionsYamlView(View):
    """
    Ручка отдаёт в yaml роли/права, доступные для сервисов (tvm приложений)
    """
    def get(self, request, *args, **kwargs):
        data = [{'slug': f'permissions.{s}', 'name': n} for s, n in SERVICE_PERMISSIONS]
        response_data = io.StringIO()
        yaml.dump(data, response_data)
        return HttpResponse(response_data.getvalue(), content_type='text/plain; charset=utf-8')


class ServiceInfoView(AuthDataMixin, CSPMixin, View):

    def get(self, request, *args, **kwargs):
        return HttpResponse(self.get_auth_data(), content_type='application/json')
