from logging import getLogger

import defence360agent.subsys.panels.hosting_panel as hp
from defence360agent.feature_management.constants import AV, FULL, PROACTIVE
from defence360agent.feature_management.lookup import features
from defence360agent.feature_management.model import FeatureManagementPerms
from defence360agent.feature_management.rpc.endpoints.utils import (
    builtin_feature_management_only,
)
from defence360agent.model.simplification import apply_order_by
from defence360agent.rpc_tools.lookup import (
    CommonEndpoints,
    RootEndpoints,
    bind,
)

logger = getLogger(__name__)


@builtin_feature_management_only
class FeatureManagementShowRootEndpoints(RootEndpoints):
    def _adapt_value(self, item):
        for feature in AV, PROACTIVE:
            item[feature] = item[feature] == FULL
        return item

    @bind("feature-management", "list")
    async def feature_management_list(self):
        """Get list of features"""
        return {"items": list(features)}

    @bind("feature-management", "defaults")
    async def feature_management_defaults(self):
        """Get default feature permissions"""
        perm = FeatureManagementPerms.get_default()
        return {"items": self._adapt_value(perm.as_dict())}

    @bind("feature-management", "show")
    async def feature_management_show(
        self, search=None, limit=None, offset=None, order_by=None
    ):
        """Show permissions"""
        users = await hp.HostingPanel().get_domains_per_user()
        if search:
            users = {
                user: domains
                for user, domains in users.items()
                if search in user or any(map(lambda x: search in x, domains))
            }

        q = FeatureManagementPerms.select()
        if order_by:
            q = apply_order_by(order_by, FeatureManagementPerms, q)
        perms = [perm for perm in q if perm.user in users]
        perms_len = len(perms)
        if offset:
            perms = perms[offset:]
        if limit:
            perms = perms[:limit]
        result = [
            {
                "name": perm.user,
                "domains": users[perm.user],
                "features": self._adapt_value(perm.as_dict()),
            }
            for perm in perms
        ]

        return perms_len, result


class FeatureManagementShowAnyEndpoints(CommonEndpoints):
    @staticmethod
    @bind("feature-management", "get")
    async def feature_management_get(user=None):
        """Get user feature permissions"""
        perm = FeatureManagementPerms.get_perm(user)
        return {"items": perm.as_dict()}
