import time
from typing import Callable
from .message import Message

class User:
    """用户（参与对话的）类"""
    def __init__(self, _id: str, name: str, port: str = "memory"):
        self._id = _id
        self.name = name
        self.porttype = port
        self._callback = None
        self.jointime = int(time.time() * 1000)
    
    def send(self, content: str, **kwargs) -> bool:
        """向此参与者发送消息"""
        if self._callback:
            # 处理 private 参数，将其添加到 metadata 中
            metadata = kwargs.pop('metadata', {})
            if 'private' in kwargs:
                metadata['private'] = kwargs.pop('private')
            # 创建消息对象
            msg = Message(sender_id="", content=content, metadata=metadata, **kwargs)
            # 触发回调函数
            self._callback(msg)
            return True
        return False
    
    def on_receive(self, callback: Callable):
        """设置接收回调"""
        self._callback = callback
    
    def to_dict(self) -> dict:
        """转为字典"""
        return {
            "_id": self._id,
            "name": self.name,
            "port": self.porttype,
            "jointime": self.jointime
        }
    
    def __repr__(self):
        """报告信息"""
        return f"User({self.name}, {self._id})"