from XCMS_PIM.models import WorkspaceUser
from app.access_control.consts import *
from app.utils.consts import ACCESS_POINTS
from app.models.channel_model import ChannelModel
from app.models.group_model import GroupModel

# Here user have a group bits by which we can get the group ids
# Then we can get the role bits from the group ids
def get_user_role_bits(user: WorkspaceUser):
    if user.groups is None:
        return DEFAULT_FULL_ACCESS_BITS
    user_group_bits = list(user.groups)
    group_len = len(user_group_bits)
    user_group_ids = [group_len - i for i, bit in enumerate(user_group_bits) if bit == "1"]
    groups = GroupModel.objects.filter(grp_id__in=user_group_ids).values_list("grp_role", flat=True)
    role_bits_len = len(groups[0]) if groups else 0
    role_bits = ["0"] * role_bits_len
    for group in groups:
        for i, bit in enumerate(group):
            if bit == "1":
                role_bits[i] = "1"
    return role_bits


def get_user_access_dict(user: WorkspaceUser):
    role_bits = get_user_role_bits(user)
    role_bits = role_bits if role_bits else DEFAULT_FULL_ACCESS_BITS
    bit_count = len(role_bits)
    access_dict = {}
    for role_group_name in ROLES_EN.keys():
        role_group = ROLES_EN[role_group_name]
        for role, value in role_group.items():
            access_dict[role] = role_bits[bit_count - value] == "1"
    return access_dict


def get_access_info_by_access_point(user: WorkspaceUser, access_point: str):
    access_dict = get_user_access_dict(user)
    if access_point == ACCESS_POINTS.PRODUCT_DETAILS:
        return {
            "can_edit_product": access_dict["product_info_update"],
            "can_delete_product": access_dict["product_delete"],
            "can_propose_product": access_dict["product_proposal"],
            "can_register_product": access_dict["product_registration"],
            "can_access_private_attributes": access_dict["private_attribute_access"],
        }


def get_user_accessible_channels(user: WorkspaceUser):
    role_bits = get_user_role_bits(user)
    role_bits = role_bits if role_bits else DEFAULT_FULL_ACCESS_BITS
    bit_count = len(role_bits)
    channels = [channel for channel in ChannelModel.objects.filter(is_deleted="0").order_by("cd").values()]
    accessable_channels = [
        channel for i, channel in enumerate(channels) if role_bits[bit_count - i - CHANNEL_START_ROLE_BIT] == "1"
    ]
    return accessable_channels
