<% page_title t('titles.extended_search') %>

<h1><%= t('extended_search.title') %></h1>

<!-- IN-PAGE TABS -->
<div class="tabBar" id="searchTabs">
  <ul>
    <li><a href="#searchTab"><%= t('extended_search.tabs.search') %></a></li>
    <li><a href="#helpTab"><%= t('extended_search.tabs.help') %></a></li>
  </ul>
</div>

<div class="formContainer">
  <div class="tabContentsWrapper">

  <!-- THE SEARCH FORM -->
  <div class="tabContentsVisible" id="searchTab">

  <form id="extendedSearchForm" accept-charset="UTF-8">
    <table>
      <tr>
        <td colspan="2">
          <%= t('extended_search.search_box_instructions') %><br>
          <textarea name="searchTerms" id="searchTerms" rows="10" autofocus></textarea>
        </td>
      </tr>

      <tr>
        <th>
          <label for="searchTermsType"><%= t('extended_search.terms_title') %></label>
        </th>
        <td>
          <select id="searchTermsType" name="searchTermsType">
            <optgroup label="<%= t('extended_search.term_names.users.title') %>">
              <option value="user-puavoid"><%= t('extended_search.term_names.users.puavoid') %></option>
              <option value="user-uid" selected><%= t('extended_search.term_names.users.uid') %></option>
              <option value="user-name-lastfirst"><%= t('extended_search.term_names.users.name_lastfirst') %></option>
              <option value="user-name-firstlast"><%= t('extended_search.term_names.users.name_firstlast') %></option>
              <option value="user-externalid"><%= t('extended_search.term_names.users.externalid') %></option>
              <option value="user-email"><%= t('extended_search.term_names.users.email') %></option>
              <option value="user-phone"><%= t('extended_search.term_names.users.phone') %></option>
            </optgroup>

            <optgroup label="<%= t('extended_search.term_names.groups.title') %>">
              <option value="group-puavoid"><%= t('extended_search.term_names.groups.puavoid') %></option>
              <option value="group-name"><%= t('extended_search.term_names.groups.name') %></option>
              <option value="group-abbreviation"><%= t('extended_search.term_names.groups.abbreviation') %></option>
              <option value="group-externalid"><%= t('extended_search.term_names.groups.externalid') %></option>
            </optgroup>

            <optgroup label="<%= t('extended_search.term_names.devices.title') %>">
              <option value="device-puavoid"><%= t('extended_search.term_names.devices.puavoid') %></option>
              <option value="device-hostname"><%= t('extended_search.term_names.devices.hostname') %></option>
              <option value="device-image"><%= t('extended_search.term_names.devices.image') %></option>
              <option value="device-current-image"><%= t('extended_search.term_names.devices.current_image') %></option>
              <option value="device-mac"><%= t('extended_search.term_names.devices.mac') %></option>
              <option value="device-tags"><%= t('extended_search.term_names.devices.tags') %></option>
              <option value="device-monitors-xml"><%= t('extended_search.term_names.devices.monitors_xml') %></option>
              <option value="device-xrandr"><%= t('extended_search.term_names.devices.xrandr') %></option>
              <option value="device-kernel-params"><%= t('extended_search.term_names.devices.kernel_params') %></option>
              <option value="device-kernel-version"><%= t('extended_search.term_names.devices.kernel_version') %></option>
              <option value="device-manufacturer"><%= t('extended_search.term_names.devices.manufacturer') %></option>
              <option value="device-model"><%= t('extended_search.term_names.devices.model') %></option>
              <option value="device-serial-number"><%= t('extended_search.term_names.devices.serial_number') %></option>
            </optgroup>
          </select>
        </td>
      </tr>

      <tr id="perTermSettingsRow">
        <th><%= t('extended_search.per_term_settings.title') %></th>
        <td>

          <div id="termSettingsUsers" class="termSettings hidden">
            <fieldset>
              <legend><%= t('extended_search.per_term_settings.deletion_mark_state.title') %></legend>

              <input type="radio" name="userType" id="userTypeMarkedForDeletion">
              <label for="userTypeMarkedForDeletion"><%= t('extended_search.per_term_settings.deletion_mark_state.is_marked') %></label><br>

              <input type="radio" name="userType" id="userTypeNormal">
              <label for="userTypeNormal"><%= t('extended_search.per_term_settings.deletion_mark_state.is_unmarked') %></label><br>

              <input type="radio" name="userType" id="userTypeAll" checked>
              <label for="userTypeAll"><%= t('extended_search.per_term_settings.deletion_mark_state.dont_care') %></label><br>
            </fieldset>

            <fieldset>
              <legend><%= t('extended_search.per_term_settings.lock_state.title') %></legend>

              <input type="radio" name="isLocked" id="lockSet">
              <label for="lockSet"><%= t('extended_search.per_term_settings.lock_state.is_locked') %></label><br>

              <input type="radio" name="isLocked" id="lockUnset">
              <label for="lockUnset"><%= t('extended_search.per_term_settings.lock_state.is_unlocked') %></label><br>

              <input type="radio" name="isLocked" id="lockIgnore" checked>
              <label for="lockIgnore"><%= t('extended_search.per_term_settings.lock_state.dont_care') %></label><br>
            </fieldset>
          </div>

          <div id="termSettingsDevices" class="termSettings hidden">
            <fieldset>
              <legend><%= t('extended_search.per_term_settings.device_type.title') %></legend>

              <input type="checkbox" name="deviceTypeLaptop" id="deviceTypeLaptop" checked>
              <label for="deviceTypeLaptop"><%= t('extended_search.per_term_settings.device_type.laptop') %></label><br>

              <input type="checkbox" name="deviceTypeFatclient" id="deviceTypeFatclient" checked>
              <label for="deviceTypeFatclient"><%= t('extended_search.per_term_settings.device_type.fatclient') %></label><br>

              <input type="checkbox" name="deviceTypePrinter" id="deviceTypePrinter" checked>
              <label for="deviceTypePrinter"><%= t('extended_search.per_term_settings.device_type.printer') %></label><br>

              <input type="checkbox" name="deviceTypeServer" id="deviceTypeBootserver" checked>
              <label for="deviceTypeBootserver"><%= t('extended_search.per_term_settings.device_type.bootserver') %></label><br>

              <input type="checkbox" name="deviceTypeOther" id="deviceTypeOther" checked>
              <label for="deviceTypeOther"><%= t('extended_search.per_term_settings.device_type.other') %></label><br>
            </fieldset>
          </div>

          <div id="noPerTermSettings" class="termSettings hidden">
            <p><%= t('extended_search.per_term_settings.no_extra_settings') %></p>
          </div>
        </td>
      </tr>

      <tr>
        <th><label for="schoolLimit"><%= t('extended_search.school_limit_title') %></label></th>

        <td>
          <select id="schoolLimit" name="schoolLimit">
            <% if current_user.organisation_owner? %>
            <option value="" selected><%= t('extended_search.school_limit_all') %></option>
            <% end %>
            <% school_list.each do |school| %>
            <% next if school.puavoTag.include?("hidden")%>
            <option value="<%= school.puavoId %>"><%= school.displayName %></option>
            <% end %>
          </select>
        </td>
      </tr>

      <tr>
        <th><%= t('extended_search.more_settings.title') %></th>
        <td>
          <input type="checkbox" name="isRegexp" id="isRegexp" checked>
          <label for="isRegexp"><%= t('extended_search.more_settings.regexp_title') %></label><br>

          <input type="checkbox" name="isReverse" id="isReverse">
          <label for="isReverse"><%= t('extended_search.more_settings.reverse_title') %></label><br>

          <input type="checkbox" name="removeMisses" id="removeMisses">
          <label for="removeMisses"><%= t('extended_search.more_settings.remove_misses_title') %></label><br>
        </td>
      </tr>

      <tr class="buttonRow">
        <td colspan="2">
          <input type="button" id="searchButton" value="<%= t('extended_search.button_search') %>"/>
          <input type="button" id="clearResultsButton" value="<%= t('extended_search.button_clear_results') %>"/>
          <input type="button" id="clearTermsButton" value="<%= t('extended_search.button_clear_terms') %>"/>
        </td>
      </tr>
    </table>
  </form>
  </div>

  <!-- SEARCH HELP -->
  <div class="tabContentsInvisible" id="helpTab">
    <% if I18n.locale.to_s == 'fi' %>
    <%= render :partial => 'help_fi' %>
    <% else %>
    <%= render :partial => 'help_en' %>
    <% end %>
  </div>  <!-- #helpTab -->

  </div>  <!-- .tabContentsWrapper -->

</div>  <!-- .formContainer -->

<!-- RESULTS -->
<h3 id="extendedSearchResultsTitle"><%= t('extended_search.results_title') %></h3>
<div id="extendedSearchResultsContainer"></div>

<% content_for :javascript do %>

<%= javascript_include_tag 'inpage_tabs', skip_pipeline: true %>

<script>

function getUsersType()
{
    if (document.querySelector("input#userTypeMarkedForDeletion").checked)
        return "marked_for_deletion";

    if (document.querySelector("input#userTypeNormal").checked)
        return "normal";

    return "all";
}

function getUsersLocked()
{
    if (document.querySelector("input#lockSet").checked)
        return "locked";

    if (document.querySelector("input#lockUnset").checked)
        return "unlocked";

    return "ignore";
}

function doSearch()
{
    const data = {
        "searchTerms": document.querySelector("textarea#searchTerms").value,
        "searchTermsType": document.querySelector("select#searchTermsType").value,
        "schoolLimit": document.querySelector("select#schoolLimit").value,
        "isRegexp": document.querySelector("input#isRegexp").checked,
        "isReverse": document.querySelector("input#isReverse").checked,
        "removeMisses": document.querySelector("input#removeMisses").checked,

        "perTermSettings": {
              "devices": {
                  "laptop": document.querySelector("input#deviceTypeLaptop").checked,
                  "fatclient": document.querySelector("input#deviceTypeFatclient").checked,
                  "printer": document.querySelector("input#deviceTypePrinter").checked,
                  "bootserver": document.querySelector("input#deviceTypeBootserver").checked,
                  "other": document.querySelector("input#deviceTypeOther").checked,
              },

              "users": {
                  "type": getUsersType(),
                  "locked": getUsersLocked(),
              },
        },
    };

    document.querySelector("input#searchButton").disabled = true;

    fetch("/extended_search", {
        method: "POST",
        mode: "cors",
        headers: {
            "Content-type": "application/json",
            "X-CSRF-Token": document.querySelector("meta[name='csrf-token']").content,
        },
        body: JSON.stringify(data),
    }).then(response => {
        if (!response.ok)
            throw response;

        return response.text();
    }).then(data => {
        document.querySelector("div#extendedSearchResultsContainer").innerHTML = data;
    }).catch(error => {
        console.error(error);
    }).finally(() => {
        document.querySelector("input#searchButton").disabled = false;
    });
}

// Extra settings for some search term types
const SEARCH_TERM_SETTINGS = {
    "user-puavoid": "termSettingsUsers",
    "user-uid": "termSettingsUsers",
    "user-name-lastfirst": "termSettingsUsers",
    "user-name-firstlast": "termSettingsUsers",
    "user-externalid": "termSettingsUsers",
    "user-email": "termSettingsUsers",
    "user-phone": "termSettingsUsers",
    "device-puavoid": "termSettingsDevices",
    "device-hostname": "termSettingsDevices",
    "device-image": "termSettingsDevices",
    "device-current-image": "termSettingsDevices",
    "device-mac": "termSettingsDevices",
    "device-tags": "termSettingsDevices",
    "device-monitors-xml": "termSettingsDevices",
    "device-xrandr": "termSettingsDevices",
    "device-kernel-params": "termSettingsDevices",
    "device-kernel-version": "termSettingsDevices",
    "device-manufacturer": "termSettingsDevices",
    "device-model": "termSettingsDevices",
    "device-serial-number": "termSettingsDevices",
};

function showOrHidePerTermSettings()
{
    const currentType = document.querySelector("select#searchTermsType").value;
    let found = false;

    if (currentType in SEARCH_TERM_SETTINGS) {
        // Have extra settings for this type, show the relevant section
        const targetId = SEARCH_TERM_SETTINGS[currentType];

        document.querySelectorAll("div.termSettings").forEach(t => {
            if (t.id == targetId) {
                t.classList.remove("hidden");
                found = true;
            } else t.classList.add("hidden");
        });
    } else {
        // No extra settings for this type, hide them all
        document.querySelectorAll("div.termSettings").forEach(t => t.classList.add("hidden"));
    }

    document.querySelector("div#noPerTermSettings").classList.toggle("hidden", found);
}

document.addEventListener("DOMContentLoaded", () => {
    new Tabs("searchTabs", 0);

    document.querySelector("select#searchTermsType")
        .addEventListener("change", () => showOrHidePerTermSettings());

    showOrHidePerTermSettings();

    document.querySelector("input#searchButton").addEventListener("click", () => doSearch());

    document.querySelector("input#clearResultsButton").addEventListener("click", () =>
        document.querySelector("div#extendedSearchResultsContainer").innerText = null);

    document.querySelector("input#clearTermsButton").addEventListener("click", () =>
        document.querySelector("textarea#searchTerms").value = null);
});

</script>
<% end %>
