# coding: utf-8

from django.conf import settings
from yarl import URL

from procu.api import models
from procu.api.utils import is_previewable
from procu.rest import serializers


class AttachmentSerializer(serializers.ModelSerializer):
    class Meta:
        model = models.Attachment
        fields = ('id', 'file', 'filename', 'created_at')
        read_only_fields = ('filename', 'created_at')


class AttachmentEntrySerializer(serializers.ModelSerializer):

    preview = serializers.SerializerMethodField()

    class Meta:
        model = models.Attachment
        fields = ('id', 'filename', 'preview', 'created_at')

    def get_preview(self, instance):

        try:
            user = self.context['request'].user
            if not user.is_staff:
                return

        except (KeyError, TypeError, AttributeError):
            return

        if is_previewable(instance.file.name):
            url = URL(settings.DOCVIEWER_HOST).with_query(
                url=f'ya-procu://{instance.id}/{instance.file.name}'
            )
            return str(url)


class DocViewerQuery(serializers.Serializer):
    attachment = serializers.CharField(required=True)
    uid = serializers.IntegerField(required=True)
