# coding: utf-8


from idm.core.workflow.plain.user import (
    UserWrapper as PlainUserWrapper,
    all_heads_of as plain_all_heads_of,
    get_head_of as plain_get_head_of,
    get_head_of_or_zam as plain_get_head_of_or_zam,
    get_department_zams as plain_get_department_zams
)
from idm.core.workflow.sandbox.manager.sanboxed import SandboxedMixin
from idm.core.workflow.sandbox.serializable import Serializable
from idm.users.models import User


def userify(login_or_user):
    if login_or_user is None:
        result = login_or_user
    elif isinstance(login_or_user, UserWrapper):
        result = login_or_user
    elif isinstance(login_or_user, User):
        result = UserWrapper(login_or_user)
    else:
        result = UserWrapper(User.objects.get(username=login_or_user))
    return result


def try_userify(login_or_user):
    try:
        return userify(login_or_user)
    except User.DoesNotExist:
        return None


class UserWrapper(SandboxedMixin, Serializable, PlainUserWrapper):
    ALLOWED_METHODS = [
        'get_chain_of_heads', 'get_tvm_app_responsibles', 'has_role', 'get_full_name', 'get_short_name', 'get_boss',
        'is_head_of', 'get_username', 'works_in_dep', 'get_boss_or_zam', 'get_robot_owners', 'is_boss_of',
        'is_external',
    ]
    ALLOWED_PROPERTIES = [
        'department_group', 'first_name', 'last_name', 'email', 'actual_mobile_phone',
        'internal_head', 'is_homeworker', 'is_robot', 'lang_ui',
        'head', 'all_heads', 'username', 'is_tvm_app', 'is_active', 'all_roles', 'groups', 'departments_chain',
        'date_joined',
    ]
    INITIAL_PROPERTIES = [
       'email', 'is_robot', 'is_tvm_app', 'is_homeworker',
    ]

    userify_func = staticmethod(userify)  # новая версия для песочницы

    @staticmethod
    def groupify_func(thing):
        from idm.core.workflow.sandbox.manager.group import groupify
        return groupify(thing)

    @classmethod
    def from_dict(cls, data, context=None):
        user = User.objects.get(username=data['username'])
        rank = data['rank']
        priority = data['priority']
        return cls(user, context=context, rank=rank, priority=priority)

    def _as_dict(self):
        return {
            'username': self.username,
            'rank': self.rank,
            'priority': self.priority,
        }

    @property
    def departments_chain(self):
        from idm.core.workflow.sandbox.manager.group import groupify
        groups = super().departments_chain.select_related(None).prefetch_related(None)
        return [groupify(x) for x in groups]

    @property
    def department_group(self):
        from idm.core.workflow.sandbox.manager.group import groupify
        self._user.fetch_department_group()
        return groupify(self._user.department_group)

    def get_chain_of_heads(self, *args, **kwargs):
        from idm.core.workflow.sandbox.manager.approver import AnyApprover
        plain_approvers = super(UserWrapper, self).get_chain_of_heads(*args, **kwargs)
        return AnyApprover(plain_approvers)


def all_heads_of(dep_slug):
    heads = plain_all_heads_of(dep_slug)
    return [userify(x) for x in heads]


def get_head_of(dep_slug):
    head = plain_get_head_of(dep_slug)
    return userify(head._user)  # PlainUserWrapper -> SandboxedUserWrapper


def get_head_of_or_zam(dep_slug):
    head = plain_get_head_of_or_zam(dep_slug)
    return userify(head._user)  # PlainUserWrapper -> SandboxedUserWrapper


def get_department_zams(dep_slug):
    zams = plain_get_department_zams(dep_slug)
    return [userify(x) for x in zams]  # PlainUserWrapper -> SandboxedUserWrapper
