<% content_for :javascript do %>
<%= javascript_include_tag 'password_validator' %>
<% end %>

<% if @have_primus %>
<p class="genericWarning"><%= t(@is_new_user ? 'users.form.primus_warning_new' : 'users.form.primus_warning_edit') %></p>
<% end %>

<% if @is_new_user && @have_gsuite %>
<p class="genericWarning"><%= t('users.form.gsuite_duplicate_prevention') %></p>
<% end %>

<p class="requiredTitle"><%= t('layouts.forms.required_field')%></p>

<%= form_for(@user, url: path, html: { method: method, multipart: true })  do |f| %>
  <table class="editForm">
    <tr>
      <th class="requiredField"><%= f.label :givenName %></th>
      <td><%= f.text_field :givenName, :required => 'required', :autofocus => @is_new_user ? true : nil %></td>
    </tr>

    <tr>
      <th class="requiredField"><%= f.label :sn %></th>
      <td><%= f.text_field :sn, :required => 'required' %></td>
    </tr>

    <tr>
      <th class="requiredField"><%= f.label :uid %></th>
      <td><%= f.text_field :uid, :required => 'required' %></td>
    </tr>

    <tr>
    <% if @automatic_email_addresses %>
      <th><%= f.label t('users.edit.automatic_email'), nil %></th>
      <% if @is_new_user %>
      <td><span id="automaticEmail"><%= @user.mail %></span></td>
      <% else %>
      <td><span id="automaticEmail"><%= Array(@user.mail).first %></span></td>
      <% end %>
    <% else %>
      <th><%= f.label :mail, nil, for: "user_mail_0" %></th>
      <td>
        <div>
        <% if Array(@user.mail).empty? %>
          <input name='user[mail][]' type='text' id='user_mail_0'/>
        <% else %>
          <% verified = Array(@user.puavoVerifiedEmail || []).to_set %>
          <% unless verified.empty? %>
          <p class="genericNotice"><%= t('users.edit.have_verified_addresses') %></p>
          <% end %>
          <% Array(@user.mail).each_with_index do |a, index| %>
          <input  id="<%= "user_mail_#{index}" %>" name="user[mail][]" type="text" value="<%= a %>"
          <% if verified.include?(a) %> readonly<% end %>/>
          <% end %>
        <% end %>
        </div>
        <%= link_to "#", class: "clone_prev_input_element btn" do %>
        <i class="icon-plus"></i><%= t('.add_email') %>
        <% end %>
        <%= field_error_text_span(f.object, :mail) %>
      </td>
    <% end %>
    </tr>

    <tr>
      <th><%= f.label :telephoneNumber, nil, for: "user_telephone_0" %></th>
      <td>
        <span>
        <% if Array(@user.telephoneNumber).empty? %>
          <input name='user[telephoneNumber][]' id='user_telephone_0' type='text'/>
        <% else %>
          <% Array(@user.telephoneNumber).each_index do |index| %>
          <input id='<%= "user_telephone_#{index}" %>' name='user[telephoneNumber][]' type='text' value='<%= Array(@user.telephoneNumber)[index] %>'/>
          <% end %>
        <% end %>
        </span>
        <%= link_to "#", class: "clone_prev_input_element btn" do %>
          <i class="icon-plus"></i><%= t('.add_telephone_number') %>
        <% end %>
        <%= field_error_text_span(f.object, :telephoneNumber) %>
      </td>
    </tr>

    <tr>
      <th class="requiredField">
      <%= f.label :puavoEduPersonAffiliation %>
      </th>
      <td class="rolesCell">
        <% User.puavoEduPersonAffiliation_list.map do |a| %>
          <input <%= @edu_person_affiliation.include?(a) ? ' checked="checked"' : "" %> id="puavoEduPersonAffiliation_<%= a %>" name="user[puavoEduPersonAffiliation][]" type="checkbox" value="<%= a %>"/>
          <label for="puavoEduPersonAffiliation_<%= a %>"><%= h t('puavoEduPersonAffiliation_' + a) %></label><br>
        <% end %>
        <%= field_error_text_span(f.object, :puavoEduPersonAffiliation) %>
        <p class="hidden genericWarning" id="conflictingRoles"><%= t('.conflicting_roles') %></p>
      </td>
    </tr>

    <tr>
      <th><%= f.label :groups %></th>
      <td id="groupsCell">
        <% if @groups_by_school.empty? %>
        (<%= t('.no_groups') %>)
        <% else %>
        <div class="flex-rows gap-10px">
          <div class="groupsFilter">
            <input type="search" class="search" placeholder="<%= t('.group_search_placeholder') %>">
          </div>
          <div class="groupsList">
            <% @groups_by_school.each do |s| %>
            <div class="school">
              <h4 class="margin-0"><%= s[:school_name] %></h4>
              <ul class="no-list-bullets margin-0 padding-0">
                <% s[:groups].each do |g| %>
                <li class="padding-left-20px" data-group-name="<%= g[:name_sort] %>">
                  <input type="checkbox" name="groups[]" id="<%= g[:id] %>" value="<%= g[:id] %>" <%= g[:member_dn].include?(@is_new_user ? '' : @user.dn.to_s) ? "checked" : "" %>><label for="<%= g[:id] %>"><%= h g[:name] %> (<%= g[:member_dn].count %> <%= t('.members') %><%= g[:type] ? ", #{g[:type]}" : "" %>)</label>
                </li>
                <% end %>
              </ul>
            </div>
            <% end %>
            <div class="hidden noMatches"><%= t('.no_group_search_hits') %></div>
          </div>
        </div>
        <% end %>
      </td>
    </tr>

    <tr>
      <th><%= f.label :puavoLocale %></th>
      <td><%= f.select :puavoLocale, locales_for_select %></td>
    </tr>

    <tr>
      <th><%= f.label :puavoEduPersonPersonnelNumber %></th>
      <td><%= f.text_field :puavoEduPersonPersonnelNumber %></td>
    </tr>

    <tr>
      <th><%= f.label :image %></th>
      <td><%= f.file_field(:image, accept: 'image/*') %></td>
    </tr>

    <tr>
      <th><%= f.label :puavoLocked %></th>
      <td><%= f.check_box :puavoLocked %></td>
    </tr>

    <% if @permit_edit_expiration_times && !@user.puavoDoNotDelete %>
    <tr>
      <th><%= f.label :puavoEduPersonAccountExpirationTime %></th>
      <td>
          <div class="flex-cols gap-5px">
            <input type="datetime-local" id="user_puavoEduPersonAccountExpirationTime" autocomplete="off" step="1">

            <button type="button" id="clearExpirationTime"><%= t('expiration_times.clear') %></button>

            <select id="setExpirationTime" autocomplete="off">
                <option value="" disabled selected hidden><%= t('expiration_times.presets') %></option>
                <%= expiration_time_presets %>
            </select>
          </div>

          <input type="hidden" id="expirationValue" name="expirationValue" autocomplete="off" value="<%= @user.puavoEduPersonAccountExpirationTime.nil? ? '' : @user.puavoEduPersonAccountExpirationTime.to_i %>">
      </td>
    </tr>
    <% end %>

    <% if current_user.organisation_owner? %>
    <tr class="ownersOnly">
      <th><%= f.label :puavoSshPublicKey %></th>
      <td><%= f.text_area :puavoSshPublicKey, cols: 80, rows: 10 %></td>
    </tr>
    <% end %>

    <tr>
      <th><%= f.label :puavoExternalId %></th>
      <td><%= f.text_field :puavoExternalId %></td>
    </tr>

    <tr>
      <th><%= f.label :puavoNotes %></th>
      <td><%= f.text_area :puavoNotes, rows: 10, class: 'resize-v' %></td>
    </tr>

    <tr>
      <th class="requiredField"><%= f.label :new_password %></th>
      <td>
      <% if @pw_warning == :none %>
        <% unless @is_admin_school %>
        <%= show_password_requirements(@organisation_name, @school.id) %>
        <% end %>
        <%= f.password_field :new_password, value: @user.new_password  %>
      <% elsif @pw_warning == :new %>
        <p class="genericNotice"><%= t('users.form.password_sync_new') %></p>
      <% elsif @pw_warning == :edit %>
        <p class="genericNotice"><%= t('users.form.password_sync_edit') %></p>
        <%= show_password_requirements(@organisation_name, @school.id) %>
        <%= f.password_field :new_password, value: @user.new_password  %>
      <% end %>
      </td>
    </tr>

    <% if @pw_warning == :none || @pw_warning == :edit %>
    <tr>
      <th class="requiredField"><%= f.label :new_password_confirmation %></th>
      <td><%= f.password_field :new_password_confirmation, value: @user.new_password_confirmation %>
      </td>
    </tr>
    <% end %>

    <tr class="buttonRow">
      <td colspan="2">
        <%= f.submit submit_text, class: 'btn' %>
        <div class="cancel"><%=link_to t('link.cancel'),  path, class: 'btn btn-danger' %></div>
      </td>
    </tr>
  </table>
<% end %>

<% unless @is_admin_school %>
<% content_for :post_load_javascript do %>
<%= setup_password_validator(@organisation_name,
                             @school.id,
                             'user_new_password',
                             'user_new_password_confirmation',
                             ['user_givenName', 'user_sn', 'user_uid']) %>
<% end %>
<% end %>

<% content_for :post_load_javascript do %>
<script>
<% if @automatic_email_addresses %>
// Automatically generate the email address. This is only for the show, the actual
// address is generated server-side, using same logic.
const DOMAIN = "<%= @automatic_email_domain %>";

let uid = document.getElementById("user_uid"),
    email = document.getElementById("automaticEmail");

function autogenerateEmailAddress()
{
    const v = uid.value.trim();

    if (v.length == 0)
        email.innerText = "";
    else email.innerText = `${v}@${DOMAIN}`;
}

uid.addEventListener("input", e => autogenerateEmailAddress());
<% end %>

function getRoleSelector(role)
{
    return document.querySelector(`table.editForm td.rolesCell input[id=puavoEduPersonAffiliation_${role}]`);
}

function updateRoles()
{
    const isStudent = getRoleSelector("student").checked,
          isTeacherOrStaff = getRoleSelector("teacher").checked || getRoleSelector("staff").checked;

    if (isStudent && isTeacherOrStaff)
        document.querySelector("p#conflictingRoles").classList.remove("hidden");
    else document.querySelector("p#conflictingRoles").classList.add("hidden");
}

// Filter the groups list
function filterGroups()
{
    const filter = document.querySelector(`table.editForm td#groupsCell .search`).value.toLowerCase().trim();

    const container = document.querySelector("table.editForm td#groupsCell div.groupsList"),
          schools = container.querySelectorAll("div.school")
          noHits = container.querySelector("div.noMatches");

    let numVisibleSchools = 0;

    for (const school of schools) {
        // Filter the groups in this school and then show/hide the whole school section
        // if nothing under it is visible
        let numVisibleGroups = 0;

        for (const group of school.querySelectorAll("li")) {
            if (filter.length == 0) {
                group.classList.remove("hidden");
                numVisibleGroups++;
                continue;
            }

            if (group.dataset.groupName.includes(filter)) {
                group.classList.remove("hidden");
                numVisibleGroups++;
            } else group.classList.add("hidden");
        }

        if (numVisibleGroups > 0) {
            school.classList.remove("hidden");
            numVisibleSchools++;
        } else school.classList.add("hidden");
    }

    if (numVisibleSchools == 0)
        noHits.classList.remove("hidden");
    else noHits.classList.add("hidden");
}

for (let cb of document.querySelectorAll("table.editForm td.rolesCell input[id^=puavoEduPersonAffiliation_]"))
    cb.addEventListener("click", () => { updateRoles(); });

<% unless @groups_by_school.empty? %>
document.querySelector(`table.editForm td#groupsCell .search`).addEventListener("input", () => filterGroups());
<% end %>

// Initial updates
updateRoles();

<% unless @groups_by_school.empty? %>
filterGroups();
<% end %>

<% if @permit_edit_expiration_times && !@user.puavoDoNotDelete %>
<%= render partial: 'shared/expiration_time_editor', locals: {
        expirationTimeField: "input#user_puavoEduPersonAccountExpirationTime",
        clearExpirationTimeButton: "button#clearExpirationTime",
        expirationPresetsSelect: "select#setExpirationTime",
        expirationValue: "input#expirationValue",
        initialExpirationTime: @user.puavoEduPersonAccountExpirationTime.nil? ? nil : @user.puavoEduPersonAccountExpirationTime
    } %>
<% end %>

</script>
<% end %>
