<!DOCTYPE html>
<html>
  <head>
    <title>Test Results</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta charset="UTF-8">
    <title>{% block title %}{% endblock %}</title>

    {% if expectation_suite_name %}
      {% set expectation_suite_name_dot_count = expectation_suite_name.count(".") -%}
    {% endif %}

    {% if "ValidationResults" in renderer_type or "ProfilingResults" in renderer_type %}
      {% set static_images_dir = ((expectation_suite_name_dot_count + 4) * "../") + "static/images/" -%}
    {% elif "ExpectationSuite" in renderer_type %}
      {% set static_images_dir = ((expectation_suite_name_dot_count + 1) * "../") + "static/images/" -%}
    {% elif "SiteIndex" in renderer_type %}
      {% set static_images_dir = "./static/images/" -%}
    {% endif %}

    {# {# Remove this when not debugging: #}
    {# <meta http-equiv="refresh" content="1"/> #}
    <link rel="stylesheet" href="{{ static_images_dir + "bootstrap-table.min.css" }}">
    <link rel="stylesheet" href="{{ static_images_dir + "bootstrap.min.css" }}">
    <link rel="stylesheet" type="text/css" href="{{ static_images_dir + "bootstrap-table-filter-control.min.css" }}">
    <link rel="stylesheet" type="text/css" href="{{ static_images_dir + "bootstrap-datepicker.min.css" }}">

    <style>{% include 'data_docs_default_styles.css' %}</style>
    <style>{% include 'data_docs_custom_styles.css' ignore missing %}</style>

    {% if "ValidationResults" in renderer_type or "ProfilingResults" in renderer_type %}
      {% set static_scripts_dir = "../../../../../static/scripts/" -%}
    {% elif "ExpectationSuite" in renderer_type %}
      {% set static_scripts_dir = "../../../../static/scripts/" -%}
    {% elif "SiteIndex" in renderer_type %}
      {% set static_scripts_dir = "./static/scripts/" -%}
    {% endif %}

    <script src="https://cdn.jsdelivr.net/npm/vega@5"></script>
    <script src="https://cdn.jsdelivr.net/npm/vega-lite@4"></script>
    <script src="https://cdn.jsdelivr.net/npm/vega-embed@6"></script>
    <link rel="stylesheet" href="{{ static_images_dir + "all.min.css" }}">

    <script src="{{ static_images_dir + "jquery-3.4.1.min.js" }}"></script>
    <script src="{{ static_images_dir + "popper.min.js" }}"></script>
    <script src="{{ static_images_dir + "bootstrap.min.js" }}"></script>
    <script src="{{ static_images_dir + "bootstrap-table.min.js" }}"></script>
    <script src="{{ static_images_dir + "bootstrap-table-filter-control.min.js" }}"></script>
    <script src="{{ static_images_dir + "bootstrap-datepicker.min.js" }}"></script>

    {% include 'favicon.j2' %}
  </head>

  <body>

    {% if renderer_type in ["ValidationResultsPageRenderer", "ExpectationSuitePageRenderer"] and show_how_to_buttons | default(True) %}
      {% include 'edit_expectations_instructions_modal.j2' %}
    {% endif %}

    {% include 'top_navbar.j2' %}

    <div class="container-fluid pt-4 pb-4 pl-5 pr-5">
      <div class="row">
        {% include 'sidebar.j2' %}
        <div class="col-md-10 col-lg-10 col-xs-12 pl-md-4 pr-md-3">
        {% for section in sections %}
          {% set section_loop = loop -%}
          {% include 'section.j2' %}
        {% endfor %}
        </div>
      </div>
    </div>

    
    <style>
      footer {
        display: none;
      }

      @media (prefers-color-scheme: dark) {
        .table {
          color: #212529 !important;
          background-color: #f1f1f1
        }
        .table-bordered{
          border: #212529;
        }
        .table-hover tbody tr:hover {
          color: #212529;
          background-color: #f1f1f1
        }
        .form-control:disabled,
        .form-control[readonly]{
          background-color: #343a40;
          opacity: .8;
        }

        .bg-light {
          background: inherit !important;
        }

        .code-snippet {
          background: #CDCDCD !important;
        }

        .alert-secondary a {
          color: #0062cc;
        }

        .alert-secondary a:focus, .alert-secondary a:hover{
          color: #004fa5;
        }

      }

      .gx-download-btn {
        position: fixed;
        top: 20px;
        right: 32px;
        font-size: 12px;
        background-color: #001861;
        color: white;
        padding: 6px 12px;
        border-radius: 5px;
        cursor: pointer;
        z-index: 10000;
        width: 235px;
        text-align: center;
      }
      .gx-download-btn:hover {
        background-color: #223a83;
      }
      .gx-download-btn[data-downloading="true"] {
        background-color: #666;
        cursor: not-allowed;
      }
      .gx-download-btn .tooltip {
        visibility: hidden;
        width: 235px;
        background-color: #333;
        color: #fff;
        text-align: center;
        border-radius: 6px;
        padding: 8px;
        position: absolute;
        z-index: 1001;
        top: 125%;
        left: 50%;
        margin-left: -117px;
        opacity: 0;
        transition: opacity 0.3s;
        font-size: 11px;
        line-height: 1.3;
      }
      .gx-download-btn .tooltip::after {
        content: "";
        position: absolute;
        bottom: 100%;
        left: 50%;
        margin-left: -5px;
        border-width: 5px;
        border-style: solid;
        border-color:  transparent transparent #333 transparent;
      }
      .gx-download-btn:hover .tooltip {
        visibility: visible;
        opacity: 1;
      }
      .ge-breadcrumbs {
        padding-right: 300px !important;
      }
    </style>

    <script>
      document.querySelectorAll('.bg-dark').forEach(function(el) {
        el.classList.remove('bg-dark');
      });

    let isResultPage = Boolean(Array.from(document.querySelectorAll('h4')).find(h => 
      h.textContent.trim() === 'Expectation Validation Result'
    ));
    let btnId = 'k-gx-download-btn';

    const resetBtnStyle = () => {
      let btn = document.getElementById(btnId);
      if(!btn)return;
      btn.innerHTML = 'DOWNLOAD UNEXPECTED VALUES<span class="tooltip">Click to download unexpected results for all tests in this run. 100 unexpected results included for each test</span>'
      btn.setAttribute("data-downloading", false)
    }

    const setBtnDownloading = () => {
      let btn = document.getElementById(btnId);
      if(!btn)return;
      btn.innerHTML = 'DOWNLOADING...<span class="tooltip">File download in progress.<br><br>This may take some time depending on the amount of unexpected values.</span>';
      btn.setAttribute("data-downloading", true)
    }

    if(isResultPage && !document.getElementById(btnId)){
      let el = document.createElement('div');
      el.id = btnId;
      el.className = 'gx-download-btn';
      document.body.appendChild(el);
      resetBtnStyle();

      el.onclick = function() {
        if(el.getAttribute("data-downloading") === "true") {
          return;
        }
        let parts = window.location.pathname.replace(/\.html$/,'').split('/').slice(-4).map(decodeURIComponent);
        const [
          suite_name,
          checkpoint_name,
          timestamp,
          batch_id
        ] = parts;

        const workspace_id = decodeURIComponent(window.location.pathname.split('/kdq/workspace/')[1].split('/')[0]);

        setBtnDownloading();

        // Build query parameters for the download request
        const queryParams = new URLSearchParams({
          workspace_id,
          suite_name,
          checkpoint_name,
          run_timestamp: timestamp,
          batch_id
        });
        
        const url = `/kdq/workspace/${workspace_id}/results/download?${queryParams.toString()}`
        let fileName;
        fetch(url, {
          method: 'GET',
          headers: {
            'Content-Type': 'application/json'
          }
        })
        .then(response => {
          if (!response.ok) {
            console.error('Download failed:', `HTTP error! status: ${response.status}`);
            alert('Download failed. Please try again.');
            resetBtnStyle();
            return;
          }
          fileName = response.headers.get('Content-Disposition')?.split('filename=')[1]?.replace(/"/g, '');
          return response.blob();
        })
        .then(blob => {
          const url = window.URL.createObjectURL(blob);
          const a = document.createElement('a');
          a.href = url;
          // name of the file, to be changed based on requirements
          a.download = fileName;
          document.body.appendChild(a);
          a.click();
          document.body.removeChild(a);
          window.URL.revokeObjectURL(url);
          resetBtnStyle();
        })
        .catch(error => {
          console.error('Download failed:', error);
          alert('Download failed. Please try again.');
          resetBtnStyle();
        });
      };
    }
    if(!isResultPage && document.getElementById(btnId)){
      document.getElementById(btnId).remove();
    }
    </script>

  </body>
</html>
