module.controller(
  "LiiibreGroupUserCtl",
  function LiiibreGroupUserCtl(
    $scope,
    $route,
    $translate,
    User,
    UserGroupMapping,
    UserGroupMembership,
    Notifications
  ) {
    const { realm, group } = $route.current.params;

    $scope.query = "";
    $scope.users = [];
    $scope.memberIds = [];

    $scope.search = () => {
      User.query(
        {
          realm,
          search: $scope.query,
          first: 0,
          max: 5,
        },
        (users) => {
          console.log(users);

          $scope.users = [];
          for (const user of users) {
            UserGroupMembership.query({ realm, userId: user.id }, (groups) => {
              user.isMember = !!groups.find((x) => x.id == group);
              $scope.users.push(user);
            });
          }
        }
      );
    };

    $scope.clearSearch = () => {
      $scope.query = "";
      $scope.users = [];
    };

    $scope.join = (id) => {
      console.log(id);
      UserGroupMapping.update(
        {
          realm,
          userId: id,
          groupId: group,
        },
        () => {
          Notifications.success($translate.instant("user.groups.join.success"));
          $scope.search();
        }
      );
    };

    $scope.leave = (id) => {
      console.log(id);
      UserGroupMapping.remove(
        {
          realm,
          userId: id,
          groupId: group,
        },
        () => {
          Notifications.success(
            $translate.instant("user.groups.leave.success")
          );
          $scope.search();
        }
      );
    };
  }
);
