/** Nextcloud OCS share permission bits (files & folders). */
export const NC_SHARE_PERM = {
  read: 1,
  update: 2,
  create: 4,
  delete: 8,
} as const

export type FolderSharePermissionId =
  | "viewContent"
  | "addFiles"
  | "modifyFiles"
  | "deleteFiles"

export type FolderSharePermissions = Record<FolderSharePermissionId, boolean>

export const FOLDER_SHARE_PERMISSION_OPTIONS: {
  id: FolderSharePermissionId
  label: string
  bit: number
}[] = [
  { id: "viewContent", label: "Voir le contenu", bit: NC_SHARE_PERM.read },
  { id: "addFiles", label: "Ajouter des fichiers", bit: NC_SHARE_PERM.create },
  { id: "modifyFiles", label: "Modifier des fichiers", bit: NC_SHARE_PERM.update },
  { id: "deleteFiles", label: "Supprimer des fichiers", bit: NC_SHARE_PERM.delete },
]

export function folderPermissionsFromRole(
  role: "viewer" | "editor"
): FolderSharePermissions {
  if (role === "editor") {
    return {
      viewContent: true,
      addFiles: true,
      modifyFiles: true,
      deleteFiles: true,
    }
  }
  return {
    viewContent: true,
    addFiles: false,
    modifyFiles: false,
    deleteFiles: false,
  }
}

export function folderPermissionsToBitmask(permissions: FolderSharePermissions): number {
  let value = 0
  for (const option of FOLDER_SHARE_PERMISSION_OPTIONS) {
    if (permissions[option.id]) value |= option.bit
  }
  return value
}

export function sharePermCanRead(perms: number) {
  return (perms & NC_SHARE_PERM.read) !== 0
}

export function sharePermCanUpdate(perms: number) {
  return (perms & NC_SHARE_PERM.update) !== 0
}

export function sharePermCanCreate(perms: number) {
  return (perms & NC_SHARE_PERM.create) !== 0
}

export function sharePermCanDelete(perms: number) {
  return (perms & NC_SHARE_PERM.delete) !== 0
}

export function sharePermCanEdit(perms: number) {
  return sharePermCanUpdate(perms) || sharePermCanCreate(perms) || sharePermCanDelete(perms)
}
