<!DOCTYPE html>
<html>
  <head>
    <meta http-equiv="content-type" content="text/html; charset=utf-8" />
    <title>Images</title>
    <script type="text/javascript" src="{{ url_for('static', filename='vendor/jquery/jquery.js') }}" charset="utf-8"></script>
    <link rel="stylesheet" type="text/css" href="{{ url_for('static', filename='css/styles.css') }}" />
    <link rel="stylesheet" type="text/css" href="/theme/current">
    <link rel="stylesheet" type="text/css" href="/theme/custom_styles">
  </head>

  <body>
    <div id="termimagesearch" class="container">

      <!-- form post is handled via javascript, added below -->
      <form id="manual_image_upload" method="post" enctype="multipart/form-data" style="display: none">
        <input type="hidden" name="langid" value="{{ langid }}">
        <input type="hidden" name="text" value="{{ text }}">
        <input type="file" name="manual_image_file" id="manual_image_file" />
      </form>

      <p class="termimagesearchtitle">
        Click an image below,
        <span id="upload_image_link" class="imageAction">upload an image</span>, or
        <span class="imageAction" title="Click to set focus in this window">click here</span>
        then paste from your clipboard.
      </p>

      {% for image in images %}
      <span class="initial"
            style="margin: 2px; display:inline-block;"
            onmouseover="highlight_image(this);"
            onmouseout="un_highlight_image(this);"
            onclick='save_image_locally("{{ image['src'] }}", {{ langid }}, "{{ text }}")'
            >
        {{ image['html'] | safe }}
      </span>
      {% endfor %}
    </div>
  </body>

  <script>

    let update_term_form = function(filename) {
      // Well, this took **far** too long to figure out ...
      let fr = window.parent.frames['wordframe'];
      if (fr == null) {
        // This feels clumsy.  Summary of bad code: this imagesearch
        // file is used on the reading pane, where it is presented as a
        // child iframe inside _another_ iframe.  It is _also_ used on
        // the term index page, where it is an iframe, but _not_ inside
        // another iframe.  In this latter case, there is no
        // window.parent.frames['wordframe'].
        //
        // There is probably a much better way of doing this,
        // but I don't know what it is, and can't be bothered to spend
        // the time to make this code more "pure."  Suggestions welcome!
        fr = window.parent;
      }
      var el = fr.document.getElementById('current_image');
      el.value = filename;
      const img = fr.document.getElementById('term_image');
      // image block initially has no size to not take up space
      img.style.gridColumn = "-1";
      img.style.display = "block";

      // Ugly hack: we have to remove the .jpeg at the end, because
      // Symfony doesn't handle params with periods.
      // Ref https://github.com/symfony/symfony/issues/25541.
      // The src/ImageController adds the .jpeg at the end again to
      // find the actual file.
      var timestamp = new Date().getTime();
      const newsrc = filename.replace('.jpeg', '') + `?${timestamp}`;
      // console.log(`switching source to ${newsrc}`);
      img.src = newsrc;
    }

    function save_image_locally(src, langid, text) {
      $.ajax({
        url: '/bing/save',
        data: {
          src: src,
          langid: langid,
          text: text
        },
        type: 'POST',
        dataType: 'json',
        success: function(data) {
          // console.log("Saved: " + data + "\nStatus: " + status);
          update_term_form(data.filename);
          $('.saved').removeClass('saved');
          $('.highlight').addClass('saved').removeClass('highlight');
        }
      });
    }

    function highlight_image(el) {
      $(el).addClass('highlight');
    }

    function un_highlight_image(el) {
      $(el).removeClass('highlight');
    }


    $(document).ready(function() {
      $('#manual_image_upload').submit(function(event) {
        event.preventDefault();
        var formData = new FormData(this);
        $.ajax({
          url: '/bing/manual_image_post',
          type: 'POST',
          data: formData,
          processData: false,
          contentType: false,
          success: function(data) {
            // console.log("Saved: " + data + "\nStatus: " + status);
            update_term_form(data.filename);
          },
          error: function(xhr, status, error) {
            console.error(`Error submitting form.  ${error}; ${status}; ${xhr.responseText}`);
          }
        });
      });

      $(window).on('paste', function(event) {
        const e = event.originalEvent;
        if (e && e.clipboardData && e.clipboardData.files) {
          $("#manual_image_file").prop('files', e.clipboardData.files);
          $('#manual_image_upload').submit();
        }
      });

      $("#upload_image_link").on('click', function(event) {
        $("#manual_image_file").click();
      });

      $("#manual_image_file").on('change', function(event) {
        event.preventDefault();
        $('#manual_image_upload').submit();
      });

    });

  </script>

</html>
