# Copyright 2021-2022 The Debusine Developers
# See the AUTHORS file at the top-level directory of this distribution
#
# This file is part of Debusine. It is subject to the license terms
# in the LICENSE file found in the top-level directory of this
# distribution. No part of Debusine, including this file, may be copied,
# modified, propagated, or distributed except according to the terms
# contained in the LICENSE file.

"""Mapping database models to REST Api support."""

from rest_framework import serializers

from debusine.db.models import WorkRequest


class WorkRequestSerializer(serializers.ModelSerializer):
    """Serializer of a WorkRequest."""

    def __init__(self, *args, **kwargs):
        """
        Initialize object.

        :param kwargs['only_fields']: it not None: any field in .data that does
          not will make validate() raise a ValidationError.
        """
        self._only_fields = kwargs.pop('only_fields', None)
        super().__init__(*args, **kwargs)

    def validate(self, data):
        """
        Add extra validation in the WorkRequest. Used by .is_valid().

        -if only_fields was passed in the __init__: raise ValidationError
          if the initial data had an unexpected field.
        """
        if self._only_fields is not None:
            fields_in_data = set(self.initial_data.keys())
            wanted_fields = set(self._only_fields)

            if unwanted_fields := (fields_in_data - wanted_fields):
                unwanted_fields = ', '.join(sorted(unwanted_fields))
                raise serializers.ValidationError(
                    f'Invalid fields: {unwanted_fields}'
                )

        return data

    class Meta:
        model = WorkRequest
        fields = [
            'id',
            'task_name',
            'created_at',
            'started_at',
            'completed_at',
            'duration',
            'worker',
            'task_name',
            'task_data',
            'status',
            'result',
        ]


class WorkerRegisterSerializer(serializers.Serializer):
    """Serializer for the data when a worker is registering."""

    token = serializers.CharField(max_length=64)
    fqdn = serializers.CharField(max_length=400)


class WorkRequestCompletedSerializer(serializers.ModelSerializer):
    """Serializer for the data when a work request is completed."""

    result = serializers.ChoiceField(choices=WorkRequest.Results)

    class Meta:
        model = WorkRequest
        fields = ['result']
