# Create your views here.
import glob
from pathlib import Path

from django.conf import settings
from django.shortcuts import render
from django.views.decorators.cache import cache_page
from rest_framework.decorators import api_view
from rest_framework.response import Response
from wagtail.models import Page

from vbv_lernwelt.core.middleware.auth import django_view_authentication_exempt


@api_view(['GET'])
@cache_page(60 * 60 * 8, cache="learning_path_cache")
def page_api_view(request, slug):
    page = Page.objects.get(slug=slug, locale__language_code='de-CH')
    serializer = page.specific.get_serializer_class()(page.specific)
    return Response(serializer.data)


@django_view_authentication_exempt
def generate_web_component_icons(request):
    svg_files = []
    for filepath in glob.iglob(f'{settings.APPS_DIR}/static/icons/*.svg'):
        with open(filepath, 'r') as f:
            filename = Path(filepath).stem
            elementname = 'it-' + filename
            svg_files.append({
                'filepath': filepath,
                'content': f.read(),
                'filename': filename,
                'elementname': elementname,
                'classname': filename.replace('-', '_'),
            })
    return render(
        request, "learnpath/icons.html",
        context={'svg_files': svg_files},
        content_type="application/javascript"
    )
