# Copyright 2020 The StackStorm Authors.
# Copyright 2019 Extreme Networks, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import six

from mongoengine import ValidationError
from st2api.controllers import resource
from st2common import log as logging
from st2common.exceptions.actionalias import ActionAliasAmbiguityException
from st2common.exceptions.apivalidation import ValueValidationException
from st2common.models.api.action import ActionAliasAPI
from st2common.persistence.actionalias import ActionAlias
from st2common.rbac.types import PermissionType
from st2common.rbac.backends import get_rbac_backend
from st2common.router import abort
from st2common.router import Response
from st2common.util.actionalias_matching import get_matching_alias
from st2common.util.actionalias_helpstring import generate_helpstring_result


http_client = six.moves.http_client

LOG = logging.getLogger(__name__)


class ActionAliasController(resource.ContentPackResourceController):
    """
    Implements the RESTful interface for ActionAliases.
    """

    model = ActionAliasAPI
    access = ActionAlias
    supported_filters = {"name": "name", "pack": "pack"}

    query_options = {"sort": ["pack", "name"]}

    _custom_actions = {"match": ["POST"], "help": ["POST"]}

    def get_all(
        self,
        exclude_attributes=None,
        include_attributes=None,
        sort=None,
        offset=0,
        limit=None,
        requester_user=None,
        **raw_filters,
    ):
        return super(ActionAliasController, self)._get_all(
            exclude_fields=exclude_attributes,
            include_fields=include_attributes,
            sort=sort,
            offset=offset,
            limit=limit,
            raw_filters=raw_filters,
            requester_user=requester_user,
        )

    def get_one(self, ref_or_id, requester_user):
        permission_type = PermissionType.ACTION_ALIAS_VIEW
        return super(ActionAliasController, self)._get_one(
            ref_or_id, requester_user=requester_user, permission_type=permission_type
        )

    def match(self, action_alias_match_api):
        """
        Find a matching action alias.

        Handles requests:
            POST /actionalias/match
        """
        command = action_alias_match_api.command

        try:
            format_ = get_matching_alias(command=command)
        except ActionAliasAmbiguityException as e:
            LOG.exception(
                'Command "%s" matched (%s) patterns.', e.command, len(e.matches)
            )
            return abort(http_client.BAD_REQUEST, six.text_type(e))

        # Convert ActionAliasDB to API
        action_alias_api = ActionAliasAPI.from_model(format_["alias"])
        return {
            "actionalias": action_alias_api,
            "display": format_["display"],
            "representation": format_["representation"],
        }

    def help(self, filter, pack, limit, offset, **kwargs):
        """
        Get available help strings for action aliases.

        Handles requests:
            GET /actionalias/help
        """
        try:
            aliases_resp = super(ActionAliasController, self)._get_all(**kwargs)
            aliases = [ActionAliasAPI(**alias) for alias in aliases_resp.json]
            return generate_helpstring_result(
                aliases, filter, pack, int(limit), int(offset)
            )
        except (TypeError) as e:
            LOG.exception(
                "Helpstring request contains an invalid data type: %s.",
                six.text_type(e),