# -*- coding: utf-8 -*-

"""
The MIT License (MIT)

Copyright (c) 2015-present Noritem

Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
"""

from .enums import PollLayoutType, try_enum

__all__ = (
    'Poll',
    'PollMedia',
    'PollAnswer',
    'PollResults',
    'PollAnswerCount',
)


class PollMedia:
    """Represents poll media (text and optional emoji).

    Attributes
    ----------
    text: Optional[:class:`str`]
        The text of the field.
    emoji: Optional[:class:`dict`]
        The emoji of the field.
    """

    __slots__ = ('text', 'emoji')

    def __init__(self, data):
        self.text = data.get('text')
        self.emoji = data.get('emoji')

    def to_dict(self):
        d = {}
        if self.text is not None:
            d['text'] = self.text
        if self.emoji is not None:
            d['emoji'] = self.emoji
        return d

    def __repr__(self):
        return '<PollMedia text={0.text!r}>'.format(self)


class PollAnswer:
    """Represents a poll answer.

    Attributes
    ----------
    answer_id: Optional[:class:`int`]
        The ID of the answer.
    poll_media: :class:`PollMedia`
        The data of the answer.
    """

    __slots__ = ('answer_id', 'poll_media')

    def __init__(self, data):
        self.answer_id = data.get('answer_id')
        self.poll_media = PollMedia(data.get('poll_media', {}))

    def to_dict(self):
        d = {}
        if self.answer_id is not None:
            d['answer_id'] = self.answer_id
        d['poll_media'] = self.poll_media.to_dict()
        return d

    def __repr__(self):
        return '<PollAnswer answer_id={0.answer_id} poll_media={0.poll_media!r}>'.format(self)


class PollAnswerCount:
    """Represents a vote count for a poll answer.

    Attributes
    ----------
    id: :class:`int`
        The answer_id.
    count: :class:`int`
        The number of votes.
    me_voted: :class:`bool`
        Whether the current user voted for this answer.
    """

    __slots__ = ('id', 'count', 'me_voted')

    def __init__(self, data):
        self.id = data['id']
        self.count = data['count']
        self.me_voted = data.get('me_voted', False)

    def __repr__(self):
        return '<PollAnswerCount id={0.id} count={0.count}>'.format(self)


class PollResults:
    """Represents poll results.

    Attributes
    ----------
    is_finalized: :class:`bool`
        Whether the votes have been precisely counted.
    answer_counts: List[:class:`PollAnswerCount`]
        The counts for each answer.
    """

    __slots__ = ('is_finalized', 'answer_counts')

    def __init__(self, data):
        self.is_finalized = data.get('is_finalized', False)
        self.answer_counts = [PollAnswerCount(a) for a in data.get('answer_counts', [])]

    def __repr__(self):
        return '<PollResults is_finalized={0.is_finalized} answers={1}>'.format(self, len(self.answer_counts))


class Poll:
    """Represents a poll attached to a message.

    Attributes
    ----------
    question: :class:`PollMedia`
        The question of the poll.
    answers: List[:class:`PollAnswer`]
        The answers available.
    expiry: Optional[:class:`str`]
        ISO8601 timestamp when the poll ends.
    allow_multiselect: :class:`bool`
        Whether users can select multiple answers.
    layout_type: :class:`PollLayoutType`
        The layout type of the poll.
    results: Optional[:class:`PollResults`]
        The results of the poll, if available.
    """

    __slots__ = ('_state', 'question', 'answers', 'expiry',
                 'allow_multiselect', 'layout_type', 'results',
                 '_channel_id', '_message_id')

    def __init__(self, *, state=None, data, channel_id=None, message_id=None):
        self._state = state
        self._channel_id = channel_id
        self._message_id = message_id
        self.question = PollMedia(data.get('question', {}))
        self.answers = [PollAnswer(a) for a in data.get('answers', [])]
        self.expiry = data.get('expiry')
        self.allow_multiselect = data.get('allow_multiselect', False)
        self.layout_type = try_enum(PollLayoutType, data.get('layout_type', 1))
        results = data.get('results')
        self.results = PollResults(results) if results else None

    def __repr__(self):
        return '<Poll question={0.question!r} answers={1}>'.format(self, len(self.answers))

    async def end(self):
        """|coro|

        Immediately ends the poll.
        Requires the message to be authored by the bot.
        """
        if self._state and self._channel_id and self._message_id:
            await self._state.http.end_poll(self._channel_id, self._message_id)

    async def get_voters(self, answer_id, *, after=None, limit=None):
        """|coro|

        Gets the users that voted for a specific answer.

        Parameters
        ----------
        answer_id: :class:`int`
            The answer ID to get voters for.
        after: Optional[:class:`int`]
            Get users after this user ID.
        limit: Optional[:class:`int`]
            Max number of users to return.

        Returns
        -------
        :class:`dict`
            The response data with voter information.
        """
        if self._state and self._channel_id and self._message_id:
            return await self._state.http.get_answer_voters(
                self._channel_id, self._message_id, answer_id,
                after=after, limit=limit,
            )
