/*
 * Copyright (C) 2018 - present Instructure, Inc.
 *
 * This file is part of Canvas.
 *
 * Canvas is free software: you can redistribute it and/or modify it under
 * the terms of the GNU Affero General Public License as published by the Free
 * Software Foundation, version 3 of the License.
 *
 * Canvas is distributed in the hope that it will be useful, but WITHOUT ANY
 * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
 * A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
 * details.
 *
 * You should have received a copy of the GNU Affero General Public License along
 * with this program. If not, see <http://www.gnu.org/licenses/>.
 */

import htmlEscape from "escape-html";
import formatMessage from "../../../format-message";
import clickCallback from "./clickCallback";

tinymce.create("tinymce.plugins.InstructureImagePlugin", {
  init: function(ed) {
    // Register commands
    ed.addCommand(
      "mceInstructureImage",
      clickCallback.bind(this, ed, document)
    );

    // Register buttons
    ed.ui.registry.addToggleButton("instructure_image", {
      title: htmlEscape(
        formatMessage({
          default: "Embed Image",
          description: "Title for RCE button to embed an image"
        })
      ),
      onAction: () => ed.execCommand("mceInstructureImage"),
      icon: "image",
      onSetup: function(buttonApi) {
        // highlight our button when an image is selected
        const toggleActive = eventApi => {
          buttonApi.setActive(
            eventApi.element.nodeName.toLowerCase() === "IMG" &&
              eventApi.element.className !== "equation_image"
          );
        };
        ed.on("NodeChange", toggleActive);
        return () => ed.off("NodeChange", toggleActive);
      }
    });
  }
});

// Register plugin
tinymce.PluginManager.add(
  "instructure_image",
  tinymce.plugins.InstructureImagePlugin
);

@@ -1088,14 +1088,12 @@
 .add
-Toggle
+Menu
 Butt
@@ -1125,20 +1125,22 @@
 %0A      t
-itle
+ooltip
 : htmlEs
@@ -1193,19 +1193,14 @@
 t: %22
-Embed 
 Image
+s
 %22,%0A 
@@ -1292,82 +1292,534 @@
     
-onAction: () =%3E ed.execCommand(%22mceInstructureImage%22),%0A      icon: %22image%22
+icon: %22image%22,%0A      fetch: (callback) =%3E %7B%0A        const items = %5B%0A          %7B%0A            type: 'menuitem',%0A            text: formatMessage('Upload Image'),%0A            onAction: () =%3E ed.execCommand(%22mceInstructureImage%22),%0A          %7D,%0A          %7B%0A            type: 'menuitem',%0A            text: formatMessage('Course Images'), // This item needs to be adjusted to be user/context aware, i.e. User Images%0A            onAction: () =%3E alert('A tray should open here :)')%0A          %7D%0A        %5D%0A        callback(items);%0A      %7D
 ,%0A  

Switch plugin to use dropdown menu