/* 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 tooltips are shown on img and canvas tags in the
// markup-view and that the tooltip actually contains an image and shows the
// right dimension label

const PAGE_CONTENT = [
  '<img class="local" src="chrome://branding/content/about-logo.png" />',
  '<img class="data" src="data:image/png;base64,[encoded data, 4412 characters]" />',
  '<img class="remote" src="' + TEST_URL_ROOT + 'doc_markup_tooltip.png" />',
  '<canvas class="canvas" width="600" height="600"></canvas>'
].join("\n");

const TEST_NODES = [
  {selector: "img.local", size: "192" + " \u00D7 " + "192"},
  {selector: "img.data", size: "64" + " \u00D7 " + "64"},
  {selector: "img.remote", size: "22" + " \u00D7 " + "23"},
  {selector: ".canvas", size: "600" + " \u00D7 " + "600"}
];

add_task(function*() {
  yield addTab("data:text/html,markup view tooltip test");
  createPage();

  let {inspector} = yield openInspector();

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

  for (let testNode of TEST_NODES) {
    let target = yield getImageTooltipTarget(testNode, inspector);
    yield assertTooltipShownOn(target, inspector);
    checkImageTooltip(testNode, inspector);
  }
});

function createPage() {
  info("Fill the page with the test content");
  content.document.body.innerHTML = PAGE_CONTENT;

  info("Fill the canvas");
  let doc = content.document;
  let context = doc.querySelector(".canvas").getContext("2d");

  context.beginPath();
  context.moveTo(300, 0);
  context.lineTo(600, 600);
  context.lineTo(0, 600);
  context.closePath();
  context.fillStyle = "#ffc821";
  context.fill();
}

function* getImageTooltipTarget({selector}, inspector) {
  let nodeFront = yield getNodeFront(selector, inspector);
  let isImg = nodeFront.tagName.toLowerCase() === "img";

  let container = getContainerForNodeFront(nodeFront, inspector);

   let target = container.editor.tag;
   if (isImg) {
     target = container.editor.getAttributeElement("src");
   }
  return target;
}

function* assertTooltipShownOn(element, {markup}) {
  info("Is the element a valid hover target");
  let isValid = yield markup.tooltip.isValidHoverTarget(element);
  ok(isValid, "The element is a valid hover target for the image tooltip");
}

function checkImageTooltip({selector, size}, {markup}) {
  let images = markup.tooltip.panel.getElementsByTagName("image");
  is(images.length, 1, "Tooltip for [" + selector + "] contains an image");

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

  markup.tooltip.hide();
}
