from typing import (
    Optional,
    Callable,
    Dict,
)

from messagebus import Message


class SendMessageRequestValidator(object):
    def __init__(
        self,
        component_name: str,
        token: Optional[int],
        data_type: Optional[int],
        data_validator: Optional[Callable[[bytes], bool]],
        headers_validator: Optional[Callable[[Dict[str, str]], bool]],
        callback: Callable[[Message], bool],
    ):
        self.component_name = component_name
        self.token = token
        self.data_type = data_type
        self.data_validator = data_validator
        self.headers_validator = headers_validator
        self.callback = callback

    def is_valid_for(
        self,
        to_component: str,
        message: Message,
    ):
        if self.component_name is not None and to_component != self.component_name:
            return False

        if self.token is not None and message.token != self.token:
            return False

        if self.data_type is not None and message.data_type != self.data_type:
            return False

        if self.data_validator is not None and not self.data_validator(message.data):
            return False

        if self.headers_validator is not None:
            return self.headers_validator(message.headers)

        if self.callback is not None:
            return self.callback(message)

        return True
