# -*- 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 .mixins import Hashable
from .enums import (
    AutoModTriggerType,
    AutoModEventType,
    AutoModActionType,
    AutoModKeywordPresetType,
    try_enum,
)

__all__ = (
    'AutoModRule',
    'AutoModAction',
)


class AutoModAction:
    """Represents an auto moderation action.

    Attributes
    ----------
    type: :class:`AutoModActionType`
        The type of action.
    metadata: :class:`dict`
        Additional metadata for the action.
    """

    __slots__ = ('type', 'metadata')

    def __init__(self, data):
        self.type = try_enum(AutoModActionType, data['type'])
        self.metadata = data.get('metadata', {})

    def to_dict(self):
        d = {'type': self.type.value}
        if self.metadata:
            d['metadata'] = self.metadata
        return d

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


class AutoModRule(Hashable):
    """Represents an auto moderation rule.

    Attributes
    ----------
    id: :class:`int`
        The rule's ID.
    guild_id: :class:`int`
        The guild ID.
    name: :class:`str`
        The rule name.
    creator_id: :class:`int`
        The ID of the user who created the rule.
    event_type: :class:`AutoModEventType`
        The event type.
    trigger_type: :class:`AutoModTriggerType`
        The trigger type.
    trigger_metadata: :class:`dict`
        The trigger metadata.
    actions: List[:class:`AutoModAction`]
        The actions to execute when the rule triggers.
    enabled: :class:`bool`
        Whether the rule is enabled.
    exempt_roles: List[:class:`int`]
        Role IDs exempt from the rule.
    exempt_channels: List[:class:`int`]
        Channel IDs exempt from the rule.
    """

    __slots__ = (
        '_state', 'id', 'guild_id', 'name', 'creator_id', 'event_type',
        'trigger_type', 'trigger_metadata', 'actions', 'enabled',
        'exempt_roles', 'exempt_channels',
    )

    def __init__(self, *, state, data):
        self._state = state
        self._update(data)

    def _update(self, data):
        self.id = int(data['id'])
        self.guild_id = int(data['guild_id'])
        self.name = data['name']
        self.creator_id = int(data['creator_id'])
        self.event_type = try_enum(AutoModEventType, data.get('event_type', 1))
        self.trigger_type = try_enum(AutoModTriggerType, data.get('trigger_type', 1))
        self.trigger_metadata = data.get('trigger_metadata', {})
        self.actions = [AutoModAction(a) for a in data.get('actions', [])]
        self.enabled = data.get('enabled', False)
        self.exempt_roles = [int(r) for r in data.get('exempt_roles', [])]
        self.exempt_channels = [int(c) for c in data.get('exempt_channels', [])]

    def __repr__(self):
        return '<AutoModRule id={0.id} name={0.name!r} guild_id={0.guild_id} enabled={0.enabled}>'.format(self)

    async def edit(self, *, reason=None, **fields):
        """|coro|

        Edits the auto moderation rule.

        Parameters
        ----------
        name: :class:`str`
            The rule name.
        event_type: :class:`AutoModEventType`
            The event type.
        trigger_metadata: :class:`dict`
            The trigger metadata.
        actions: List[:class:`dict`]
            The actions (list of action dicts).
        enabled: :class:`bool`
            Whether the rule is enabled.
        exempt_roles: List[:class:`int`]
            Role IDs exempt from the rule.
        exempt_channels: List[:class:`int`]
            Channel IDs exempt from the rule.
        reason: Optional[:class:`str`]
            The reason for editing.
        """
        payload = {}
        for key in ('name', 'trigger_metadata', 'enabled'):
            if key in fields:
                payload[key] = fields[key]

        if 'event_type' in fields:
            payload['event_type'] = fields['event_type'].value
        if 'actions' in fields:
            payload['actions'] = fields['actions']
        if 'exempt_roles' in fields:
            payload['exempt_roles'] = [str(r) for r in fields['exempt_roles']]
        if 'exempt_channels' in fields:
            payload['exempt_channels'] = [str(c) for c in fields['exempt_channels']]

        data = await self._state.http.edit_automod_rule(self.guild_id, self.id, reason=reason, **payload)
        self._update(data)

    async def delete(self, *, reason=None):
        """|coro|

        Deletes the auto moderation rule.

        Parameters
        ----------
        reason: Optional[:class:`str`]
            The reason for deleting.
        """
        await self._state.http.delete_automod_rule(self.guild_id, self.id, reason=reason)
