"""Quick implementation for message sending and receiving via inheritance"""

import asyncio
from typing import Any, Optional, Dict
from .message import Message, MessageType, MessagePriority
from .channel import Channel, ChannelOptions
from .subscriber import Subscriber


class MessageHandler:
    """Base class for handling messages via inheritance"""
    
    def __init__(self, channel: Optional[Channel] = None, name: str = ""):
        self.name = name or self.__class__.__name__
        self._channel = channel
        self._subscriber: Optional[Subscriber] = None
    
    async def handle_message(self, message: Message) -> Any:
        """Override this method to handle messages"""
        raise NotImplementedError
    
    def subscribe_to(self, channel: Channel, message_type: Optional[str] = None) -> Subscriber:
        """Subscribe to a channel"""
        filters = {"type": message_type} if message_type else None
        self._channel = channel
        self._subscriber = channel.subscribe(
            channel=channel.name,
            callback=self._on_message,
            name=self.name,
            filters=filters
        )
        return self._subscriber
    
    async def _on_message(self, message: Message):
        """Internal message handler"""
        result = await self.handle_message(message)
        return result
    
    def unsubscribe(self):
        """Unsubscribe from channel"""
        if self._subscriber and self._channel:
            self._channel.unsubscribe(self._subscriber.id)


class EventListener(MessageHandler):
    """Base class for event listening"""
    
    async def on_event(self, event_name: str, data: Any, message: Message):
        """Override this method to handle specific events"""
        raise NotImplementedError
    
    async def handle_message(self, message: Message) -> Any:
        """Handle incoming event message"""
        if message.type == MessageType.EVENT and message.payload:
            event_name = message.payload.get("event_name")
            event_data = message.payload.get("data")
            if event_name:
                return await self.on_event(event_name, event_data, message)


class RequestHandler(MessageHandler):
    """Base class for handling request-response messages"""
    
    async def handle_request(self, request: Message) -> Any:
        """Override this method to handle requests"""
        raise NotImplementedError
    
    async def handle_message(self, message: Message) -> Any:
        """Handle incoming request"""
        if message.type == MessageType.REQUEST:
            return await self.handle_request(message)


class ChannelClient:
    """Quick client for sending messages"""
    
    def __init__(self, channel: Channel):
        self._channel = channel
    
    async def send(self, channel_name: str, payload: Any, **kwargs) -> bool:
        """Send message to channel"""
        message = Message(channel=channel_name, payload=payload, **kwargs)
        return await self._channel.publish(message)
    
    async def emit_event(self, channel_name: str, event_name: str, data: Any = None, **kwargs) -> bool:
        """Emit event to channel"""
        message = Message(
            channel=channel_name,
            type=MessageType.EVENT,
            payload={"event_name": event_name, "data": data},
            **kwargs
        )
        return await self._channel.publish(message)
    
    async def request(
        self,
        channel_name: str,
        payload: Any,
        timeout: float = 30.0,
        **kwargs
    ) -> Optional[Message]:
        """Send request and wait for response"""
        return await self._channel.request(channel_name, payload, timeout, **kwargs)
    
    async def broadcast(self, payload: Any, **kwargs) -> bool:
        """Broadcast to all subscribers"""
        message = Message(
            channel=self._channel.name,
            type=MessageType.BROADCAST,
            payload=payload,
            **kwargs
        )
        return await self._channel.publish(message)


class SyncMessageHandler:
    """Synchronous message handler (non-async)"""
    
    def __init__(self, channel: Optional[Channel] = None, name: str = ""):
        self.name = name or self.__class__.__name__
        self._channel = channel
        self._subscriber: Optional[Subscriber] = None
    
    def handle_message(self, message: Message) -> Any:
        """Override this method to handle messages (sync version)"""
        raise NotImplementedError
    
    def subscribe_to(self, channel: Channel, message_type: Optional[str] = None) -> Subscriber:
        """Subscribe to a channel"""
        async def wrapper(msg):
            return self.handle_message(msg)
        
        filters = {"type": message_type} if message_type else None
        self._channel = channel
        self._subscriber = channel.subscribe(
            channel=channel.name,
            callback=wrapper,
            name=self.name,
            filters=filters
        )
        return self._subscriber
    
    def unsubscribe(self):
        """Unsubscribe from channel"""
        if self._subscriber and self._channel:
            self._channel.unsubscribe(self._subscriber.id)
