#  Copyright (C) 2021
#  ABM, Moscow
#
#  UNPUBLISHED PROPRIETARY MATERIAL.
#  ALL RIGHTS RESERVED.
#
#  Authors: Mike Orlov <m.orlov@abm-jsc.ru>
#
from typing import Optional, Dict

from aiohttp.typedefs import DEFAULT_JSON_DECODER

from .decoder import Decoder
from .mime_types import ContentType


class DecoderRegister:
    def __init__(self):
        self.content_type_to_decoder: Dict[ContentType, Decoder] = {
            ContentType.Json: DEFAULT_JSON_DECODER,
        }

    def register_decoder(self, content_type: ContentType, decoder: Decoder, *, allow_overwrite: bool = False) -> None:
        if content_type not in self.content_type_to_decoder or allow_overwrite:
            self.content_type_to_decoder[content_type] = decoder
        else:
            raise KeyError(
                f'Decoder for {content_type} already registered: {self.content_type_to_decoder[content_type]}. '
                f'Use arg "allow_overwrite" to overwrite value')

    def unregister_decoder(self, content_type: ContentType, *, ignore_missing: bool = False) -> None:
        if ignore_missing:
            self.content_type_to_decoder.pop(content_type, None)
        else:
            self.content_type_to_decoder.pop(content_type)

    def pick_decoder(self, content_type: Optional[ContentType]) -> Optional[Decoder]:
        return self.content_type_to_decoder.get(content_type)
