from logging import getLogger

from nperipherals_core.model.device_status import DeviceStatus
from nperipherals_core.model.repository import NotificationRepository
from nperipherals_core.service import ReaderDeviceServiceThread
from typing import Optional

from externals.device import NetworkDevice
from nperipherals_core.model.custom_exceptions import DeviceNotConnected
from nperipherals_core.model.device import ReaderDevice, DeviceServiceThread

logger = getLogger(__name__)


class NetworkScannerDevice(ReaderDevice, NetworkDevice):
    def __init__(self, device_configurations):
        super(NetworkScannerDevice, self).__init__(logger, device_configurations)

    def _create_service_thread(self, repository):
        # type: (NotificationRepository) -> Optional[DeviceServiceThread]
        return ReaderDeviceServiceThread(self, repository)

    def read(self):
        # type: () -> Optional[str]

        try:
            data = self.socket.recv(self.SOCKET_BUF_SIZE)
            if data:
                self.logger.debug("Device [{}] got data [{}]".format(self.get_name(), data))
                return data

        except Exception as e:
            self.logger.exception("Error getting socket data with error [{}]".format(repr(e)))

        raise DeviceNotConnected()

    def get_status(self):
        return DeviceStatus.Ok
