<% page_title t('titles.schools'), @user.primary_school.displayName, t('titles.users'), @user.displayName, t('.title') %>

<h1><%= t('.header', name: link_to(@user.displayName, './')).html_safe %></h1>

<% if @user_is_owner %>
<p class="genericNotice"><%= t('.user_is_owner') %><p>
<% end %>

<%
groups = [
  [ t('.title_schools'), %w[school_edit school_edit_wlan]],
  [ t('.title_users'), %w[create_users delete_users mass_delete_users import_users users_mass_clear_column_contents user_edit_expiration_times user_mass_edit_expiration_times]],
  [ t('.title_groups'), %w[create_groups delete_groups mass_delete_groups group_change_school group_mass_change_type]],
  [ t('.title_devices'), %w[create_devices delete_devices mass_delete_devices reset_devices mass_reset_devices device_change_school device_mass_change_school device_mass_tag_editor device_mass_change_purchase_information device_edit_expiration_times device_mass_edit_expiration_times device_mass_set_db_fields device_mass_edit_puavoconf]],
]
%>

<%= form_for(@user, url: save_admin_permissions_path, html: { method: :post })  do |f| %>
  <input type="hidden" name="org_admins" value="<%= @org_admins %>">

  <div class="flex-rows gap-20px" id="permissionsList">
  <% groups.each do |g| %>
    <div>
      <header><%= g[0] %></header>
      <div class="flex-rows margin-left-20px">
      <% g[1].each do |p| %>
        <div><label><input type="checkbox" name="permissions[]" id="<%= p %>" value="<%= p %>" <%= @current_permissions.include?(p) ? 'checked' : '' %> autocomplete="off"><%= t(".permissions.#{p}") %></label></div>
      <% end %>
      </div>
    </div>
  <% end %>
  </div>

  <div class="flex-cols gap-10px margin-top-10px">
    <%= f.submit t('link.update'), class: 'btn' %>
    <div class="cancel"><%=link_to t('link.cancel'), @org_admins ? all_admins_organisation_path : user_path(@school, @user), class: 'btn' %></div>
    <a href="#" id="selectAll" class="btn"><%= t('.select_all') %></a>
    <a href="#" id="deselectAll" class="btn"><%= t('.deselect_all') %></a>
  </div>
<% end %>

<% content_for :post_load_javascript do %>
<script>
"use strict";

function selectAll(event, state)
{
    event.preventDefault();

    for (const cb of document.querySelectorAll("div#permissionsList input"))
        cb.checked = state;
}

document.addEventListener("DOMContentLoaded", () => {
    document.querySelector("a#selectAll").addEventListener("click", e => selectAll(e, true));
    document.querySelector("a#deselectAll").addEventListener("click", e => selectAll(e, false));
});
</script>
<% end %>
