<!DOCTYPE html>
<html>

<head>
  <meta charset="UTF-8">
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
  <link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-icons/1.8.1/font/bootstrap-icons.min.css" rel="stylesheet">
  <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.3/moment.min.js"></script>
</head>

<body>
  <!-- tasks table -->
  <table class="table table-bordered table-striped table-hover table-sm" style="font-size: small">
    <tr>
      <th>Task ID</th>
      <th>Try Number</th>
      <th>Map Index</th>
      <th>Status</th>
      <th>Submit Time</th>
      <th>Start Time</th>
      <th>End Time</th>
      <th>Duration</th>
      <th>Logs</th>
    </tr>
    {% for job_task in job_tasks_list %}
    <tr>
      <td>{{job_task.task_id}}</td>
      <td>{{job_task.try_number}}</td>
      <td>
        {% if job_task.map_index > -1 %}
          <span>{{job_task.map_index}}</span>
        {% else %}
          <span></span>
        {% endif %}
      </td>
      <td class="{% if job_task.task_state == 'success' %}table-success
                {% elif job_task.task_state == 'failed' %}table-danger
                {% elif job_task.task_state == 'running' %}table-info
                {% elif job_task.task_state == 'queued' %}table-secondary
                {% endif %}">{{job_task.task_state}}</td>
      <td class="datetime_to_be_adjusted">{{job_task.submit_time}}</td>
      <td class="datetime_to_be_adjusted">{{job_task.start_time}}</td>
      <td class="datetime_to_be_adjusted">{{job_task.end_time}}</td>
      <td>{{job_task.duration}}</td>
      <td>
        {% if job_task.try_number > 0 %}
        <button type="button" class="btn btn-outline-primary btn-sm" data-bs-toggle="modal" data-bs-target="#logs-modal"
            data-dag-id="{{ job_task.dag_id }}"
            data-job-id="{{ job_task.job_id }}"
            data-task-id="{{ job_task.task_id }}"
            data-task-state="{{ job_task.task_state }}"
            data-task-try-number="{{ job_task.try_number }}"
            data-task-map-index="{{ job_task.map_index }}"
          ><i class="bi bi-box-arrow-up-right" title="View logs"></i>
          </button>
        {% endif %}
      </td>
    </tr>
    {% endfor %}
  </table>
  <!-- modal for displaying logs per task -->
  <div class="modal fade" id="logs-modal" tabindex="-1" aria-labelledby="logs-modal-label" aria-hidden="true">
    <div class="modal-dialog modal-fullscreen">
      <div class="modal-content">
        <div class="modal-header p-2">
          <div class="modal-title fw-bold" id="logs-modal-label" style="font-size: small">
            <span id="modal-title-task" class="me-2"></span><span id="modal-title-task-state" class="badge"></span>
          </div>
          <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
        </div>
        <div class="modal-body p-2">
            <iframe id="logs-iframe" class="w-100 h-100" src=""></iframe>
        </div>
      </div>
    </div>
  </div>
  <!-- display errors to user -->
  {% if status_code != 200 %}
  <div class="alert alert-danger" role="alert">
    <h4 class="alert-heading">{{ message }}</h4>
    <p>
      {% for error in errors %}
        {% if error is string %}{{ error }}
        {% elif error is mapping %}
          {% for key, value in error.items() %}
            <strong>{{ key }}:</strong> {{ value }}<br>
          {% endfor %}
        {% endif %}
      {% endfor %}
    </p>
  </div>
  {% endif %}
  <script>
    window.onload = function () {
      document.querySelectorAll(".datetime_to_be_adjusted").forEach(function (el) {
        if (el.innerHTML !== "") {
          var utcTime = moment.utc(el.innerText);  // This is the time in UTC
          utcTime.local();  // Switch to using the browser's local timezone
          el.innerText = utcTime.format('YYYY-MM-DD h:mm:ss a');  // Write the local time back to the element
        };
      });
      var logsModal = document.getElementById('logs-modal');
      logsModal.addEventListener('show.bs.modal', function (event) {
        var sourceData = event.relatedTarget?.dataset;
        updateTaskLogsModal(sourceData?.dagId,sourceData?.jobId, sourceData?.taskId, sourceData?.taskState,  sourceData?.taskTryNumber, sourceData?.taskMapIndex);
      })
      logsModal.addEventListener('hidden.bs.modal', function (event) {
        updateTaskLogsModal(null, null, null, null, null, null);
      })
    }
    function updateTaskLogsModal(dagId, jobId, taskId, taskState, taskTryNumber, taskMapIndex) {
      console.log('updateTaskLogsModal', dagId, jobId, taskId, taskState, taskTryNumber, taskMapIndex);
      // Update the modal header with the task id, try number, map index, and state
      var tryMapLabel = taskMapIndex > -1 ? `${taskId} (try ${taskTryNumber}, map_index ${taskMapIndex})` :  `${taskId} (try ${taskTryNumber})`;
      document.getElementById('modal-title-task').textContent = tryMapLabel;
      var modalTitleTaskState = document.getElementById('modal-title-task-state');
      modalTitleTaskState.textContent = taskState;
      if (taskState) {
        modalTitleTaskState.classList.add(
          taskState === 'success' ? 'bg-success'
          : taskState === 'failed' ? 'bg-danger'
          : taskState === 'running' ? 'bg-info'
          : 'bg-secondary'
        );
      } else {
        modalTitleTaskState.classList.value = 'badge';
      }
      // Update the iframe src to get the logs for the task
      var logsIframe = document.getElementById('logs-iframe');
      if (jobId) {
        var url = new URL("{{ url_for('task_logs') }}");
        url.searchParams.append('dag_id', dagId);
        url.searchParams.append('dag_run_id', jobId);
        url.searchParams.append('task_id', taskId);
        url.searchParams.append('try_number', taskTryNumber);
        url.searchParams.append('map_index', taskMapIndex);
        logsIframe.src = url;
      } else {
        logsIframe.src = "";
      }
    }
  </script>
</body>

</html>