from dateutil import parser
from telethon.tl.functions.messages import SearchRequest
from telethon.tl.functions.channels import CreateChannelRequest
from telethon.tl.types import InputMessagesFilterEmpty

from telefire.plugins.base import PluginMount
from telefire.telegram import TelegramCommand


class SearchMessages(TelegramCommand, metaclass=PluginMount):
    command_name = "search_messages"

    async def _search_messages_async(self, chat, query, slow, limit, user, output, before=None, after=None):
        _filter = InputMessagesFilterEmpty()
        peer = await self.client.get_entity(chat)
        if user is not None:
            user = await self.client.get_entity(user)

        offset_date = parser.parse(before) if before else None
        min_date = parser.parse(after) if after else None

        self.set_file_handler("search_messages", peer, user, query)

        if slow:
            if output == 'channel':
                result = await self.client(CreateChannelRequest(
                    "Search Messages",
                    "Messages in {}".format(peer.title)))
                output = result.chats[0]
                self.logger.info("Channel: {} created.".format(output.title))
            await self.helpers.messages.iter(
                peer,
                user,
                query,
                output,
                offset_date=offset_date,
                min_date=min_date,
            )
        else:
            search_request = SearchRequest(
                    peer=peer,
                    q=query,
                    filter=_filter,
                    min_date=min_date,
                    max_date=offset_date,
                    offset_id=0,
                    add_offset=0,
                    limit=limit,
                    max_id=0,
                    min_id=0,
                    hash=0,
                    from_id=user)
            result = await self.client(search_request)
            for msg in result.messages:
                sender = user
                if sender is None:
                    sender = await self.client.get_entity(msg.from_id)
                self.helpers.messages.log(msg, peer, sender)

    def __call__(self, chat, query, slow=False, limit=100, user=None, output='log', before=None, after=None):
        self.run_once(
            lambda: self._search_messages_async(chat, query, slow, limit, user, output, before, after)
        )
