from django.db.models import Q
from gm_dataquery.dataquery import DataBuilder
from gm_dataquery.dataquery import DataSQLQuery
from hera.models import BackendPermission, BackendGroup
from gm_dataquery.db import DB


class PermDB(DataBuilder):
    def getval_name(self, obj):
        return u'{}.{}'.format(obj.module.name, obj.name)

    def getval_title(self, obj):
        return u'{}|{}'.format(obj.module.title, obj.title)


@DB
class PermDQ(DataSQLQuery):
    model = BackendPermission
    data_model = PermDB

    def filter_title(self, srch_key, srch_val, regex):
        q = Q()
        if isinstance(srch_val, list):
            srch_val = '|'.join(srch_val)
        srch_val_list = srch_val.split('|')
        for srch_val in srch_val_list:
            q |= Q(module__title__contains=srch_val) | Q(title__contains=srch_val)
        return q


class GroupDB(DataBuilder):
    pass


@DB
class GroupDQ(DataSQLQuery):
    model = BackendGroup
    data_model = GroupDB

    def filter_username(self, srch_key, srch_val, regex):
        return Q(members__username=srch_val)
