import json

from boss.interactor.insert_or_update_users.dto import InsertOrUpdateUsersRequest
from boss.model import User
from boss_api.shared.exception import (
    InvalidDataFormat,
    MissingMandatoryField,
    NoData,
    NoUtf8Data,
)
from ._BaseProcessor import BaseProcessor


class InsertOrUpdateUsersProcessor(BaseProcessor):

    def parse_data(
        self,
        data: bytes
    ) -> InsertOrUpdateUsersRequest:

        if not data:
            raise NoData()

        try:
            data_str = data.decode()
        except UnicodeDecodeError:
            raise NoUtf8Data()

        try:
            users_dict = json.loads(s=data_str)
            users_to_insert_or_update = []
            for user in users_dict:
                if "user_id" not in user:
                    raise MissingMandatoryField()

                users_to_insert_or_update.append(
                    User(
                        user_id=int(user["user_id"]),
                        user_name=user.get("user_name"),
                        long_name=user.get("long_name"),
                        password=user.get("password"),
                        level=int(user["level"]) if "level" in user else None,
                        status=int(user["status"]) if "status" in user else None,
                        admission_date=user.get("admission_date"),
                        termination_date=user.get("termination_date"),
                        fingerprint_minutiae=user.get("fingerprint_minutiae"),
                        nfc_uuid=user.get("nfc_uuid"),
                    )
                )
        except Exception as ex:
            exception = InvalidDataFormat()
            exception.message = str(ex)
            raise exception

        return InsertOrUpdateUsersRequest(users_to_insert_or_update=users_to_insert_or_update)
