<% settings = Setting.plugin_redmine_ux_toolkit || {} %>
<% refresh_service = RedmineUxToolkit::Services::RepositoryRefresh %>
<% scheduler_enabled = refresh_service.enabled?(settings) %>
<% default_interval = refresh_service.default_interval_minutes(settings) %>
<% max_per_run = refresh_service.max_per_run(settings) %>
<% max_runtime = refresh_service.max_runtime_seconds(settings) %>
<% backoff_enabled = refresh_service.failure_backoff_enabled?(settings) %>
<% interval_options = [
  [l(:label_ux_toolkit_repository_refresh_manual_only), '0'],
  [l(:label_ux_toolkit_repository_refresh_every_30_minutes), '30'],
  [l(:label_ux_toolkit_repository_refresh_hourly), '60'],
  [l(:label_ux_toolkit_repository_refresh_every_4_hours), '240'],
  [l(:label_ux_toolkit_repository_refresh_daily), '1440']
] %>
<% repository_interval_options = [
  [l(:label_ux_toolkit_repository_refresh_use_default_interval), '-1'],
  *interval_options
] %>

<div class="ux-toolkit-settings-section">
  <p><strong><%= l(:label_ux_toolkit_repository_refresh) %></strong></p>
  <p class="info"><%= l(:text_ux_toolkit_repository_refresh_help) %></p>

  <p>
    <%= hidden_field_tag 'settings[enable_repository_refresh_scheduler]', '0', id: nil %>
    <%= check_box_tag 'settings[enable_repository_refresh_scheduler]',
                      '1',
                      scheduler_enabled,
                      id: 'settings_enable_repository_refresh_scheduler' %>
    <%= label_tag 'settings_enable_repository_refresh_scheduler',
                  l(:label_ux_toolkit_enable_repository_refresh_scheduler) %>
  </p>

  <p>
    <%= label_tag 'settings_repository_refresh_default_interval_minutes',
                  l(:label_ux_toolkit_repository_refresh_default_interval) %>
    <%= select_tag 'settings[repository_refresh_default_interval_minutes]',
                   options_for_select(interval_options, default_interval.to_s),
                   id: 'settings_repository_refresh_default_interval_minutes' %>
  </p>

  <p>
    <%= label_tag 'settings_repository_refresh_max_per_run',
                  l(:label_ux_toolkit_repository_refresh_max_per_run) %>
    <%= number_field_tag 'settings[repository_refresh_max_per_run]',
                         max_per_run,
                         min: 1,
                         max: 10,
                         step: 1,
                         id: 'settings_repository_refresh_max_per_run',
                         size: 4 %>
  </p>

  <p>
    <%= label_tag 'settings_repository_refresh_max_runtime_seconds',
                  l(:label_ux_toolkit_repository_refresh_max_runtime) %>
    <%= number_field_tag 'settings[repository_refresh_max_runtime_seconds]',
                         max_runtime,
                         min: 30,
                         max: 3600,
                         step: 30,
                         id: 'settings_repository_refresh_max_runtime_seconds',
                         size: 6 %>
  </p>

  <p>
    <%= hidden_field_tag 'settings[repository_refresh_failure_backoff]', '0', id: nil %>
    <%= check_box_tag 'settings[repository_refresh_failure_backoff]',
                      '1',
                      backoff_enabled,
                      id: 'settings_repository_refresh_failure_backoff' %>
    <%= label_tag 'settings_repository_refresh_failure_backoff',
                  l(:label_ux_toolkit_repository_refresh_failure_backoff) %>
    <br>
    <em class="info"><%= l(:text_ux_toolkit_repository_refresh_failure_backoff_help) %></em>
  </p>
</div>

<div class="ux-toolkit-settings-section">
  <p><strong><%= l(:label_ux_toolkit_repository_refresh_status) %></strong></p>

  <% if refresh_service.table_available? %>
    <% repositories = Repository.includes(:project).order(:project_id, :id).to_a %>
    <% states_by_repository = UxToolkitRepositoryRefreshState.where(repository_id: repositories.map(&:id)).index_by(&:repository_id) %>
    <% configured_states = refresh_service.repository_states %>
    <% due_count = refresh_service.due_count %>

    <table class="list">
      <tbody>
        <tr>
          <th><%= l(:label_ux_toolkit_enabled) %></th>
          <td><%= scheduler_enabled ? l(:general_text_Yes) : l(:general_text_No) %></td>
        </tr>
        <tr>
          <th><%= l(:label_ux_toolkit_repository_refresh_total_configured) %></th>
          <td><%= configured_states.size %></td>
        </tr>
        <tr>
          <th><%= l(:label_ux_toolkit_repository_refresh_due) %></th>
          <td><%= due_count %></td>
        </tr>
      </tbody>
    </table>

    <% if repositories.any? %>
      <div class="box tabular ux-toolkit-repository-refresh-bulk"
           data-ux-toolkit-repository-refresh-bulk>
        <p><strong><%= l(:label_ux_toolkit_repository_refresh_bulk_actions) %></strong></p>
        <p>
          <%= button_tag l(:button_ux_toolkit_enable_all_repositories),
                         type: 'button',
                         class: 'button-small',
                         data: {ux_toolkit_repository_refresh_bulk_enable: '1'} %>
          <%= button_tag l(:button_ux_toolkit_disable_all_repositories),
                         type: 'button',
                         class: 'button-small',
                         data: {ux_toolkit_repository_refresh_bulk_disable: '1'} %>
        </p>
        <p>
          <%= label_tag 'ux_toolkit_repository_refresh_bulk_interval',
                        l(:label_ux_toolkit_repository_refresh_bulk_interval) %>
          <%= select_tag 'ux_toolkit_repository_refresh_bulk_interval',
                         options_for_select(repository_interval_options, '-1'),
                         id: 'ux_toolkit_repository_refresh_bulk_interval',
                         data: {ux_toolkit_repository_refresh_bulk_interval: '1'} %>
          <%= button_tag l(:button_ux_toolkit_apply_interval_to_all_repositories),
                         type: 'button',
                         class: 'button-small',
                         data: {ux_toolkit_repository_refresh_bulk_apply_interval: '1'} %>
        </p>
      </div>

      <table class="list ux-toolkit-repository-refresh">
        <thead>
          <tr>
            <th><%= l(:field_project) %></th>
            <th><%= l(:label_ux_toolkit_repository) %></th>
            <th><%= l(:label_ux_toolkit_repository_type) %></th>
            <th><%= l(:label_ux_toolkit_repository_location) %></th>
            <th><%= l(:label_ux_toolkit_enabled) %></th>
            <th><%= l(:label_ux_toolkit_repository_refresh_interval) %></th>
            <th><%= l(:label_ux_toolkit_repository_refresh_last_run_at) %></th>
            <th><%= l(:label_ux_toolkit_repository_refresh_next_run_at) %></th>
            <th><%= l(:label_ux_toolkit_cron_status) %></th>
            <th><%= l(:label_ux_toolkit_repository_refresh_failures) %></th>
            <th><%= l(:button_ux_toolkit_refresh_now) %></th>
          </tr>
        </thead>
        <tbody>
          <% repositories.each do |repository| %>
            <% state = states_by_repository[repository.id] || UxToolkitRepositoryRefreshState.state_for(repository) %>
            <% row_name = "ux_toolkit_repository_refresh_states[#{repository.id}]" %>
            <% project_active = refresh_service.repository_project_active?(repository) %>
            <% refresh_interval = state.refresh_interval_minutes %>
            <tr class="<%= 'ux-toolkit-repository-refresh-inactive-project' unless project_active %>">
              <td>
                <% if repository.project %>
                  <%= link_to_project(repository.project) %>
                  <% unless project_active %>
                    <span class="ux-toolkit-muted">(<%= l(:label_ux_toolkit_project_inactive) %>)</span>
                  <% end %>
                <% else %>
                  -
                <% end %>
              </td>
              <td><%= h(repository.name) %></td>
              <td><%= h(ux_toolkit_repository_type(repository)) %></td>
              <td><%= h(ux_toolkit_repository_location_label(repository)) %></td>
              <td class="center">
                <%= hidden_field_tag "#{row_name}[repository_id]", repository.id, id: nil %>
                <%= hidden_field_tag "#{row_name}[enabled]", project_active ? '0' : (state.enabled? ? '1' : '0'), id: nil %>
                <%= check_box_tag "#{row_name}[enabled]",
                                  '1',
                                  state.enabled?,
                                  id: "ux_toolkit_repository_refresh_enabled_#{repository.id}",
                                  disabled: !project_active %>
              </td>
              <td>
                <% unless project_active %>
                  <%= hidden_field_tag "#{row_name}[refresh_interval_minutes]", refresh_interval, id: nil %>
                <% end %>
                <%= select_tag "#{row_name}[refresh_interval_minutes]",
                               options_for_select(repository_interval_options, refresh_interval.to_s),
                               id: "ux_toolkit_repository_refresh_interval_#{repository.id}",
                               disabled: !project_active %>
              </td>
              <td><%= state.last_run_at ? format_time(state.last_run_at) : '-' %></td>
              <td><%= state.next_run_at ? format_time(state.next_run_at) : '-' %></td>
              <td title="<%= h(state.last_message.to_s) %>"><%= refresh_service.status_label(state.last_status) %></td>
              <td class="center"><%= state.consecutive_failure_count.to_i %></td>
              <td class="buttons">
                <% if project_active && state.persisted? && state.enabled? %>
                  <%= link_to l(:button_ux_toolkit_refresh_now),
                              refresh_ux_toolkit_repository_path(state),
                              method: :post,
                              class: 'icon icon-reload' %>
                <% else %>
                  -
                <% end %>
              </td>
            </tr>
            <% if state.last_message.present? && state.last_status.to_s == UxToolkitRepositoryRefreshState::STATUS_FAILED %>
              <tr class="ux-toolkit-repository-refresh-message">
                <td></td>
                <td colspan="10"><%= h(state.last_message) %></td>
              </tr>
            <% end %>
          <% end %>
        </tbody>
      </table>

      <%= javascript_tag do %>
        document.addEventListener('DOMContentLoaded', function() {
          var wrapper = document.querySelector('[data-ux-toolkit-repository-refresh-bulk]');
          if (!wrapper) { return; }

          var enableButton = wrapper.querySelector('[data-ux-toolkit-repository-refresh-bulk-enable]');
          var disableButton = wrapper.querySelector('[data-ux-toolkit-repository-refresh-bulk-disable]');
          var intervalSelect = wrapper.querySelector('[data-ux-toolkit-repository-refresh-bulk-interval]');
          var applyIntervalButton = wrapper.querySelector('[data-ux-toolkit-repository-refresh-bulk-apply-interval]');

          function repositoryEnabledCheckboxes() {
            return document.querySelectorAll('.ux-toolkit-repository-refresh input[type="checkbox"][name$="[enabled]"]:not(:disabled)');
          }

          function repositoryIntervalSelects() {
            return document.querySelectorAll('.ux-toolkit-repository-refresh select[name$="[refresh_interval_minutes]"]:not(:disabled)');
          }

          if (enableButton) {
            enableButton.addEventListener('click', function() {
              Array.prototype.forEach.call(repositoryEnabledCheckboxes(), function(checkbox) {
                checkbox.checked = true;
              });
            });
          }

          if (disableButton) {
            disableButton.addEventListener('click', function() {
              Array.prototype.forEach.call(repositoryEnabledCheckboxes(), function(checkbox) {
                checkbox.checked = false;
              });
            });
          }

          if (applyIntervalButton && intervalSelect) {
            applyIntervalButton.addEventListener('click', function() {
              Array.prototype.forEach.call(repositoryIntervalSelects(), function(select) {
                select.value = intervalSelect.value;
              });
            });
          }
        });
      <% end %>
    <% else %>
      <p class="nodata"><%= l(:text_ux_toolkit_repository_refresh_no_repositories) %></p>
    <% end %>
  <% else %>
    <p class="nodata"><%= l(:text_ux_toolkit_repository_refresh_status_unavailable) %></p>
  <% end %>
</div>
