from kolibri.auth.api import KolibriAuthPermissions, KolibriAuthPermissionsFilter
from kolibri.content.content_db_router import using_content_database
from kolibri.content.models import ChannelMetadataCache, ContentNode
from kolibri.core.api import CSVModelViewSet
from rest_framework import serializers

from .models import ContentSessionLog, ContentSummaryLog


class LogCSVSerializerBase(serializers.ModelSerializer):

    username = serializers.SerializerMethodField()
    facility_name = serializers.SerializerMethodField()
    channel_name = serializers.SerializerMethodField()
    content_title = serializers.SerializerMethodField()
    time_spent = serializers.SerializerMethodField()
    progress = serializers.SerializerMethodField()

    def get_username(self, obj):
        if obj.user:
            return obj.user.username
        else:
            return ""

    def get_facility_name(self, obj):
        if obj.user:
            return obj.user.facility.name
        else:
            return ""

    def get_channel_name(self, obj):
        try:
            channel = ChannelMetadataCache.objects.get(id=obj.channel_id)
        except ChannelMetadataCache.DoesNotExist:
            return ""
        return channel.name

    def get_content_title(self, obj):
        try:
            with using_content_database(obj.channel_id):
                node = ContentNode.objects.filter(content_id=obj.content_id).first()
                if node:
                    return node.title
                else:
                    return ""
        except KeyError:  # content DB doesn't exist
            return ""

    def get_time_spent(self, obj):
        return "{:10.1f}".format(round(obj.time_spent, 1))

    def get_progress(self, obj):
        return "{:10.4f}".format(round(obj.progress, 4))


class ContentSummaryLogCSVSerializer(LogCSVSerializerBase):

    class Meta:
        model = ContentSummaryLog
        fields = ('username', 'facility_name', 'content_id', 'content_title', 'channel_id', 'channel_name', 'start_timestamp',
                  'end_timestamp', 'completion_timestamp', 'time_spent', 'progress', 'kind')
        labels = {
            "start_timestamp": "Time of first interaction",
            "end_timestamp": "Time of last interaction",
            "completion_timestamp": "Time of completion",
        }


class ContentSessionLogCSVSerializer(LogCSVSerializerBase):

    class Meta:
        model = ContentSessionLog
        fields = ('username', 'facility_name', 'content_id', 'content_title', 'channel_id', 'channel_name', 'start_timestamp',
                  'end_timestamp', 'time_spent', 'progress', 'kind')
        labels = {
            "start_timestamp": "Time of first interaction",
            "end_timestamp": "Time of last interaction",
        }


class ContentSummaryLogCSVExportViewSet(CSVModelViewSet):
    permission_classes = (KolibriAuthPermissions,)
    filter_backends = (KolibriAuthPermissionsFilter,)
    queryset = ContentSummaryLog.objects.all()
    serializer_class = ContentSummaryLogCSVSerializer
    csv_export_filename = 'content_summary_logs'


class ContentSessionLogCSVExportViewSet(CSVModelViewSet):
    permission_classes = (KolibriAuthPermissions,)
    filter_backends = (KolibriAuthPermissionsFilter,)
    queryset = ContentSessionLog.objects.all()
    serializer_class = ContentSessionLogCSVSerializer
    csv_export_filename = 'content_session_logs'

@@ -1656,28 +1656,45 @@
         
-return 
+seconds_float = float(str(
 %22%7B:
-10
 .1f%7D%22.fo
@@ -1723,16 +1723,369 @@
 ent, 1))
+))  # e.g. 30.2%0A        seconds_int = int(seconds_float)  # e.g. 30%0A        seconds_decimal = str(seconds_float)%5B-1:%5D   # e.g. 2%0A        minutes, seconds = divmod(seconds_int, 60)%0A        hours, minutes = divmod(minutes, 60)%0A        days, hours = divmod(hours, 24)%0A        return %22%25d:%2502d:%2502d:%2502d.%25s%22 %25 (days, hours, minutes, seconds, seconds_decimal)
 %0A%0A    de
@@ -2130,13 +2130,15 @@
 urn 
+str(
 %22%7B:
-10
 .4f%7D
@@ -2169,16 +2169,17 @@
 ess, 4))
+)
 %0A%0A%0Aclass
@@ -2694,24 +2694,121 @@
 ompletion%22,%0A
+            %22time_spent%22: %22Time Spent (D:HH:MM:SS.d)%22,%0A            %22progress%22: %22Progress (0-1)%22,%0A
         %7D%0A%0A%0A
@@ -3242,32 +3242,129 @@
 t interaction%22,%0A
+            %22time_spent%22: %22Time Spent (D:HH:MM:SS.d)%22,%0A            %22progress%22: %22Progress (0-1)%22,%0A
         %7D%0A%0A%0Aclas

Make time spent more human readable.