# coding: utf-8

from __future__ import unicode_literals

import attr
import types

from cab.core import logic
from cab.sources import staff, staff_api


def get_result_set_for_filter(auth, filter, paginator=None):
    if filter is None:
        return staff.DummyEmptyResultSet()

    if filter.scope == 'saved':
        return staff.get_saved_filter_persons(
            auth=auth,
            staff_saved_filter_id=filter.id,
            paginator=paginator,
        )
    elif filter.scope == 'department':
        return staff.get_department_persons(
            auth=auth,
            department_id=filter.id,
            paginator=paginator,
        )
    elif filter.scope == 'service':
        service_group = staff_api.get_service_group(
            auth=auth,
            slug=filter.id,
        )
        if service_group is None:
            return staff.DummyEmptyResultSet()
        return staff.get_service_group_persons(
            auth=auth,
            service_group_id=service_group['id'],
            paginator=paginator,
        )
    elif filter.scope == 'subordinates' and filter.id == 'all':
        return staff.get_all_subordinates(
            auth=auth,
            staff_id=auth.staff_id,
            paginator=paginator,
        )
    elif filter.scope == 'subordinates' and filter.id == 'direct':
        return staff.get_direct_subordinates(
            auth=auth,
            staff_id=auth.staff_id,
            paginator=paginator,
        )


def remember_controls(auth, persons_fields=None, persons_filter=None):
    data_for_update = {}
    if persons_fields:
        data_for_update['persons_fields'] = persons_fields
    if persons_filter:
        data_for_update['persons_filter_id'] = str(persons_filter)
    if data_for_update:
        logic.update_user_data(uid=auth.uid, **data_for_update)


def get_remembered_controls(auth):
    if 'user_data' not in auth.extra:
        auth.extra['user_data'] = logic.get_user_data(uid=auth.uid)
    return auth.extra['user_data']


@attr.s
class Filter(object):
    scope = attr.ib(validator=attr.validators.instance_of(basestring))
    id = attr.ib(validator=attr.validators.instance_of((
        int,
        basestring,
        types.NoneType
    )))

    @classmethod
    def from_str(cls, filter_id):
        if '-' in filter_id:
            scope, id = filter_id.split('-', 1)
        else:
            scope, id = filter_id, None

        try:
            id = int(id)
        except (ValueError, TypeError):
            id = id

        return cls(scope=scope, id=id)

    def __str__(self):
        str_repr = self.scope
        if self.id:
            str_repr += '-' + str(self.id)
        return str_repr
