{% include 'header.html' %}
<div class="container">
  <h4>File {{ filename }}:</h4>

  <div class="five columns">
    <p><a href="{{ url_for('index') }}">Home</a> | Search catalogues:</p>
    {% for catalog in catalogues %}
      <input class="{% if loop.first %}button-primary{% else %}button{% endif %} catalog-selection" type="button" value="{{ catalog }}">
    {% endfor %}
  </div>
  <div class="six columns" id="export-section" style="display: none">
    <p> Export current matches:</p>
    <input type="button" id="export-ttl" class="button"  value="As TTL" />
    <input type="button" id="export-jsonld" class="button"  value="As JSON-LD" />
    <input type="button" id="export-csv" class="button"  value="As Pandas CSV" />
  </div>

  <table class="u-full-width" id="search_results_table">
    <thead>
      <tr>
        <th>Name</th>
        <th>Match</th>
        <th>Action</th>
      </tr>
    </thead>
    <tbody>
      {% for row in data %}
      <tr>
        <td id="row-{{ loop.index0 }}">{{ row[0] }}<span class="tooltiptext">{{ row[1] }}</span></td>
        <td></td>
        <td><input class="button-primary row-matching" type="button" name="row-matching" id="match-row-{{ loop.index0 }}" value="Match"></td>
      </tr>
      {% endfor %}
    </tbody>
  </table>
</div>

<!-- The Modal -->
<div id="modal_match" class="modal">
  <!-- Modal content -->
  <div class="modal-content">
    <span class="close">&times;</span>


    <div class="container" style="margin-left:5%;margin-right:5%;max-width:none;">
      <div class="row"  style="width:100%">
      <div class="one-half column" style="overflow:hidden">
        <span id="item_to_match"></span>
        <input type="button" class="button-primary" id="save-match" name="save-match-button" value="Save">
      </div>
      <div class="one-half column">
        <ul>
          <h4>Match type:</h4>
          <label>
            <input type="radio" name="match_type" value="exact" class="match-type" checked>
            <span class="label-body exact">Exact match</span>
          </label>
          <label>
            <input type="radio" name="match_type" value="approximate" class="match-type">
            <span class="label-body approximate">Approximate match</span>
          </label>
          <label>
            <input type="radio" name="match_type" value="broader" class="match-type">
            <span class="label-body broader">Match is broader than query</span>
          </label>
          <label>
            <input type="radio" name="match_type" value="narrower" class="match-type">
            <span class="label-body narrower">Match is narrower than query</span>
          </label>
        </ul>
      </div>
    </div>

      <div class="row" style="width:100%">
        <div class="one-half column">
          <h4>Suggested entries</h4>
          <table id="response_table">
            <tbody>
            </tbody>
          </table>
        </div>

        <div class="one-half column">
          <h4>Refine query</h4>
          <form class="form-inline" style="margin: 0 auto;">
              <input id="refine-search-field"
                     type="search"
                     onclick="this.select();"
                     placeholder="Search for products"
                     aria-label="Search"
                     style="width:100%;">
            </form>
        </div>
      </div>
  </div>
  </div>

</div>

<!-- Import JS script -->
<script type="text/javascript">
var catalog = null;
var match_data = new Map();
match_data['hash'] = "{{ hash }}";
var match_type = "exact";
var source_row = null;
var match_row = null;


(function set_initial_catalog() {
  catalog = "{{ catalogues[0] }}";
  match_data['catalog'] = "{{ catalogues[0] }}";
})();

// Handle match type selection
var match_type_buttons = document.querySelectorAll(".match-type");
for (i = 0; i < match_type_buttons.length; i++) {
  match_type_buttons[i].addEventListener('click', toggle_match_type);
}

function toggle_match_type(button) {
    match_type = button.target.value;
    if (match_row !== null) {
      match_row.classList.remove("exact", "approximate", "broader", "narrower");
      match_row.classList.add(match_type);
    }
}

// Bring up matching modal window
var row_buttons = document.querySelectorAll(".row-matching");
for (i = 0; i < row_buttons.length; i++) {
  row_buttons[i].addEventListener('click', show_modal);
}

// Catalog selection
var catalog_buttons = document.querySelectorAll(".catalog-selection");
for (i = 0; i < catalog_buttons.length; i++) {
  catalog_buttons[i].addEventListener('click', toggle_catalog_selection);
}

function toggle_catalog_selection(button) {
    match_data['catalog'] = button.target.value;
    var all_buttons = document.querySelectorAll('.catalog-selection');
    Array.prototype.forEach.call(all_buttons, function(elements, index) {
        if (button.target.value === elements.value) {
            elements.className = "button-primary catalog-selection";
            catalog = elements.value;
        } else {
            elements.className = "button catalog-selection";
        };
    });
}

// Query catalog and reset result table
function query(query_string){
    var opts = {
      method: 'GET',
      headers: {}
    };
    fetch('/get_search_results/'+catalog+'/'+query_string, opts)
    .then(function (response) {
      return response.json();
    })
    .then(function (data) {
        var table = document.getElementById("response_table")

        // Reset table
        var tableRows = table.getElementsByTagName('tr');
        var rowCount = tableRows.length;

        for (var x=rowCount-1; x>0; x--) {
           table.removeChild(tableRows[x]);
        }

        // row is integer index starting from 0
        for (var row in data) {
          var tr = document.createElement('tr');
          var div_label = document.createElement('div');
          div_label.className="tooltip possible-match";
          div_label.innerHTML = data[row].name.slice(0,40);
          div_label.id = "match-row-" + row.toString();
          div_label.data = data[row];

          div_label.onclick = function (row) {
            match_row = row.target;
            row.target.classList.remove("exact", "approximate", "broader", "narrower");
            row.target.classList.add("selected-element", match_type);
            var all_matches = document.querySelectorAll('.possible-match');
            Array.prototype.forEach.call(all_matches, function(element, index) {
              if (row.target.id !== element.id) {
                element.classList.remove("selected-element");
              }
            });
          }

          var tooltip = document.createElement('span')
          tooltip.className = "tooltiptext";
          tooltip.innerHTML = data[row].description;
          div_label.append(tooltip);

          var td_label = document.createElement('td');
          td_label.append(div_label);

          tr.append(td_label);
          table.append(tr);
        };
    });
};

// Update result table and save model data
document.getElementById("save-match").onclick = function (event) {
  var row = source_row.children[0];
  var matched_string = '';
  // reset our saved results
  match_data[row.id] = {
    "source": row.textContent,
    "matches": new Array()
  };

  var labels = ["exact", "approximate", "narrower", "broader"];
  var matches_array = match_data[row.id]["matches"];

  // Add data from each row
  var table = document.getElementById("response_table");
  for (var i = 0, tr; tr = table.rows[i]; i++) {
    var div = tr.children[0].children[0];
    for (label of labels) {
      if (div.classList.contains(label)) {
        matches_array.push({"method": label, "data": div.data});
        matched_string += "<span class=\"" + label + "\">" + div.data.name.slice(0,40) + "</span> "
      };
    };
    source_row.children[1].innerHTML = matched_string;
  };

  document.getElementById('export-section').style.display = 'inline';
  var modal = document.getElementById('modal_match')
  modal.style.display = "none";
};


function show_modal(button){
    source_row = button.target.parentElement.parentElement;

    var span = document.getElementsByClassName("close")[0];
    // When the user clicks on <span> (x), close the modal
    span.onclick = function() {
      modal.style.display = "none";
    }
    // When the user clicks anywhere outside of the modal, close it
    window.onclick = function(event) {
      if (event.target == modal) {
        modal.style.display = "none";
      }
    }

    // Select modal
    var modal = document.getElementById('modal_match');

    // Insert titles, etc.
    var row = document.getElementById(button.target.id.replace("match-", ""));
    var row_text = row.textContent;
    var title_span = document.getElementById("item_to_match")
    title_span.innerHTML = "<h4>"+row_text+"</h4>";

    document.getElementById("refine-search-field").value = row_text;

    // Fetch data
    query(row_text);
    // Display modal
    modal.style.display = "block";
};

// Export as TTL
document.getElementById("export-ttl").onclick = function (event) {
  var xhr = new XMLHttpRequest();
  var url = "/export/ttl";
  xhr.open("POST", url, true);
  xhr.setRequestHeader("Content-Type", "application/json");

  xhr.onreadystatechange=function() {
    if (xhr.readyState==4 && xhr.status==200){
      var fp = JSON.parse(xhr.responseText).fp;
      var button = document.getElementById("export-ttl");
      var new_form = document.createElement('form');
      new_form.style = "margin: 0; padding: 0; display:inline";
      new_form.innerHTML = '<input display="inline" type="submit" class="button-primary" value="Download TTL" />';
      new_form.action = "/download/" + fp;
      button.replaceWith(new_form);
    }
  }

  var data = JSON.stringify(match_data);
  xhr.send(data);
}

// Export as JSON-LD
document.getElementById("export-jsonld").onclick = function (event) {
  var xhr = new XMLHttpRequest();
  var url = "/export/jsonld";
  xhr.open("POST", url, true);
  xhr.setRequestHeader("Content-Type", "application/json");

  xhr.onreadystatechange=function() {
    if (xhr.readyState==4 && xhr.status==200){
      var fp = JSON.parse(xhr.responseText).fp;
      var button = document.getElementById("export-jsonld");
      var new_form = document.createElement('form');
      new_form.style = "margin: 0; padding: 0; display:inline";
      new_form.innerHTML = '<input display="inline" type="submit" class="button-primary" value="Download JSON-LD" />';
      new_form.action = "/download/" + fp;
      button.replaceWith(new_form);
    }
  }

  var data = JSON.stringify(match_data);
  xhr.send(data);
}

// Export as Pandas Dataframe CSV
document.getElementById("export-csv").onclick = function (event) {
  var xhr = new XMLHttpRequest();
  var url = "/export/csv";
  xhr.open("POST", url, true);
  xhr.setRequestHeader("Content-Type", "application/json");

  xhr.onreadystatechange=function() {
    if (xhr.readyState==4 && xhr.status==200){
      var fp = JSON.parse(xhr.responseText).fp;
      var button = document.getElementById("export-csv");
      var new_form = document.createElement('form');
      new_form.style = "margin: 0; padding: 0; display:inline";
      new_form.innerHTML = '<input display="inline" type="submit" class="button-primary" value="Download Pandas CSV" />';
      new_form.action = "/download/" + fp;
      button.replaceWith(new_form);
    }
  }

  var data = JSON.stringify(match_data);
  xhr.send(data);
}

// Populate table with search results as the search field is updated.
var table = document.getElementById('refine-search-field');
table.addEventListener('input', function (evt) {
    query(this.value);
});
</script>
{% include 'footer.html' %}
