/* vim: set ts=2 et sw=2 tw=80: */
/* Any copyright is dedicated to the Public Domain.
 http://creativecommons.org/publicdomain/zero/1.0/ */

"use strict";

// Test that image preview tooltip shows updated content when the image src
// changes.

/*eslint-disable */
const INITIAL_SRC = "data:image/png;base64,[encoded data, 4412 characters]";
/*eslint-enable */

const UPDATED_SRC = URL_ROOT + "doc_markup_tooltip.png";

const INITIAL_SRC_SIZE = "64" + " \u00D7 " + "64";
const UPDATED_SRC_SIZE = "22" + " \u00D7 " + "23";

add_task(function* () {
  let { inspector } = yield openInspectorForURL(
    "data:text/html,<p>markup view tooltip test</p><img>");

  info("Retrieving NodeFront for the <img> element.");
  let img = yield getNodeFront("img", inspector);

  info("Selecting the <img> element");
  yield selectNode(img, inspector);

  info("Adding src attribute to the image.");
  yield updateImageSrc(img, INITIAL_SRC, inspector);

  let container = getContainerForNodeFront(img, inspector);
  ok(container, "Found markup container for the image.");

  let target = container.editor.getAttributeElement("src")
                               .querySelector(".link");
  ok(target, "Found the src attribute in the markup view.");

  info("Showing tooltip on the src link.");
  yield inspector.markup.tooltip.isValidHoverTarget(target);

  checkImageTooltip(INITIAL_SRC_SIZE, inspector);

  info("Updating the image src.");
  yield updateImageSrc(img, UPDATED_SRC, inspector);

  target = container.editor.getAttributeElement("src").querySelector(".link");
  ok(target, "Found the src attribute in the markup view after mutation.");

  info("Showing tooltip on the src link.");
  yield inspector.markup.tooltip.isValidHoverTarget(target);

  info("Checking that the new image was shown.");
  checkImageTooltip(UPDATED_SRC_SIZE, inspector);
});

/**
 * Updates the src attribute of the image. Return a Promise.
 */
function updateImageSrc(img, newSrc, inspector) {
  let onMutated = inspector.once("markupmutation");
  let onModified = img.modifyAttributes([{
    attributeName: "src",
    newValue: newSrc
  }]);

  return Promise.all([onMutated, onModified]);
}

/**
 * Checks that the markup view tooltip contains an image element with the given
 * size.
 */
function checkImageTooltip(size, {markup}) {
  let images = markup.tooltip.panel.getElementsByTagName("image");
  is(images.length, 1, "Tooltip contains an image");

  let label = markup.tooltip.panel.querySelector(".devtools-tooltip-caption");
  is(label.textContent, size, "Tooltip label displays the right image size");

  markup.tooltip.hide();
}
