# coding: utf-8


from idm.core.workflow.plain.system import SystemWrapper as PlainSystemWrapper
from idm.core.workflow.sandbox.manager.group import GroupWrapper
from idm.core.workflow.sandbox.manager.sanboxed import SandboxedMixin
from idm.core.workflow.sandbox.serializable import Serializable
from idm.core.workflow.sandbox.manager.user import UserWrapper


def systemify(thing):
    from idm.core.models import System
    if isinstance(thing, SystemWrapper):
        return thing
    elif isinstance(thing, str):
        thing = System.objects.get(slug=thing)
    return SystemWrapper(thing)


class SystemWrapper(SandboxedMixin, Serializable, PlainSystemWrapper):
    ALLOWED_METHODS = ['get_name', 'get_state', 'all_users_with_role', 'all_groups_with_role',
                       'get_aliased_nodes', 'get_node_by_data']
    ALLOWED_PROPERTIES = ['name', 'name_en', 'is_active', 'is_broken', 'slug', 'creator']
    INITIAL_PROPERTIES = ['slug']

    user_wrapper_class = UserWrapper
    group_wrapper_class = GroupWrapper
    _node_class = None

    def __init__(self, system, context=None):
        super(SystemWrapper, self).__init__(system)
        self.context = context

    @classmethod
    def get_node_wrapper_class(cls):
        if cls._node_class is None:
            from idm.core.workflow.sandbox.manager.node import NodeWrapper
            cls._node_class = NodeWrapper
        return cls._node_class

    @classmethod
    def from_dict(cls, data, context=None):
        from idm.core.models import System
        system_slug = data['slug']
        system = System.objects.get(slug=system_slug)
        return cls(system, context=context)

    def _as_dict(self):
        return {
            'slug': self._system.slug,
        }

    def _check_permissions(self):
        if not getattr(self, 'context', None):
            raise ValueError('context variable should be specified')
        inspecting_system = self.context['system']._system
        inspected_system = self._system
        self._check_systems(inspecting_system, inspected_system)

    def _call_from_container(self, *args, **kwargs):
        self._check_permissions()
        return super(SystemWrapper, self)._call_from_container(*args, **kwargs)
