from typing import Dict, List, Union

from nperipherals_core.model.device import ReaderDevice, WriterDevice
from nperipherals_core.model.custom_exceptions import UnknownDevice


class DeviceFactory(object):
    def __init__(self, device_types):
        # type: (List[type]) -> None

        self.handled_devices = dict()  # type: Dict[str, type]

        for device_type in device_types:
            self._register(device_type)

    def create_device(self, device_configurations):
        # type: (Dict) -> Union[ReaderDevice, WriterDevice]

        if not device_configurations or "Type" not in device_configurations:
            raise UnknownDevice()

        device_type_str = device_configurations["Type"]  # type: str

        if device_type_str in self.handled_devices:
            return self.handled_devices[device_type_str](device_configurations)

        raise UnknownDevice(device_type_str)

    def _register(self, device_type):
        # type: (type) -> None

        self.handled_devices[device_type.__name__] = device_type
