"""
messageboard.py - Client library for the class messageboard.
"""

import requests


class Message:
    """A single message on the board."""

    def __init__(self, data):
        self.id = data["id"]
        self.author = data["author"]
        self.text = data["text"]
        self.timestamp = data["timestamp"]

    def __repr__(self):
        return (
            f"Message(id={self.id}, author='{self.author}', text='{self.text}')"
        )


class Board:
    """
    A connection to the class messageboard.

    Example usage:
        board = Board("https://server-demo-dqpp.onrender.com", username="your_name")
        board.post("Hello everyone!")
        messages = board.get_recent(5)
        for msg in messages:
            print(msg.author, "said:", msg.text)
    """

    def __init__(self, url, username):
        self.url = url.rstrip("/")
        self.username = username

    def post(self, text):
        """Post a new message to the board. Returns the new Message."""
        response = requests.post(
            f"{self.url}/messages",
            json={"username": self.username, "text": text},
        )
        response.raise_for_status()
        return Message(response.json())

    def get_recent(self, n=10):
        """Get the n most recent messages. Returns a list of Messages."""
        response = requests.get(f"{self.url}/messages", params={"limit": n})
        response.raise_for_status()
        return [Message(m) for m in response.json()]

    def get_message(self, message_id):
        """Get a single message by its id. Returns a Message."""
        response = requests.get(f"{self.url}/messages/{message_id}")
        response.raise_for_status()
        return Message(response.json())

    def search(self, keyword):
        """Search messages by keyword. Returns a list of Messages."""
        response = requests.get(f"{self.url}/search", params={"q": keyword})
        response.raise_for_status()
        return [Message(m) for m in response.json()]

    def delete(self, message_id):
        """Delete one of your own messages by id."""
        response = requests.delete(
            f"{self.url}/messages/{message_id}",
            json={"username": self.username},
        )
        response.raise_for_status()
        return response.json()

    def __repr__(self):
        return f"Board(url='{self.url}', username='{self.username}')"
