<template>
  <div class="w-100">
    <editor
      tinymceScriptSrc="/tinymce/tinymce.min.js"
      ref="global-tiny-editor"
      output-format="html"
      v-model="editorData"
      :init="tinyMceConfiguration"
    >
    </editor>

    <div class="my-3" v-if="hideButton">
      <button-component
        :class="$attrs.hideButton"
        @click="save"
        type="button"
        classes="btn-primary"
        buttonText="ذخیره"
        title="ذخیره"
        :buttonLoading="buttonLoading"
      ></button-component>
    </div>
  </div>
</template>
<script>
export default {
  mounted() {
    // this.showTiny = true

    // this.$nextTick(() => {
    this.editorData = this.tinyText;
    var n = Math.floor(Math.random() * 11);
    var k = Math.floor(Math.random() * 1000000);
    var m = String.fromCharCode(n) + k;
    this.api_key = m;

    // })
  },

  props: {
    hideButton:{
      default:true
    },
    tinyText: {
      default: "",
    },
    parentButtonLoading: {
      default: false,
    },
  },

  data() {
    return {
      buttonLoading: this.parentButtonLoading,
      editorData: "",
      api_key: "",

      tinyMceConfiguration: {
        selector: "#textarea",
        apiKey: "pnxkbox1zj5zaghgi1dolyi9ch28kr9ohnvc1qz3beeqdfwg",
        menubar: false,
        statusbar: false,
        language: "fa_IR",
        language_url: "/tinymce/langs/fa_IR.js",
        directionality: "rtl",
        baseUel: "/",
        theme_url: "/tinymce/themes/silver/theme.min.js",
        toolbar_sticky: true,
        force_br_newlines: false,
        force_p_newlines: false,
        //forced_root_block : 'p',
        setup: function(editor) {
          if (editor) {
            editor.on("init", function(e) {});
            editor.on("ScrollWindow", function(e) {
              //var y1 = editor.getWin().pageYOffset;
              //var sctop = $(editor.getContainer()).scrollTop();
              if ("js_ScrollChanged" in window.external) {
                window.external.js_ScrollChanged(0);
              }
            });
            editor.on("Paste", function(e) {
              if ("js_ScrollHeightChanged" in window.external) {
                window.external.js_ScrollHeightChanged();
              }
            });
            editor.on("DblClick", function(e) {
              if (e.ctrlKey) selectParag(editor);
              else selectWord(editor);
            });
            editor.on("SelectionChange", function(e) {
              //if ('js_SelectionChange' in window.external){
              //	window.external.js_SelectionChange();
              //}
            });
            editor.on("NodeChange", function(e) {
              if ("js_NodeChange" in window.external) {
                wlast = "";
                window.external.js_NodeChange(e.element.innerText);
              }
            });
            editor.on("mousedown", function(e) {
              if ("js_mousedown" in window.external) {
                window.external.js_mousedown();
              }
            });
            editor.on("keydown", function(e) {
              if ("js_keydown" in window.external) {
                var handeled = window.external.js_keydown(e.ctrlKey, e.keyCode);
                if (handeled) {
                  e.preventDefault();
                  return false;
                }
              }

              if (checkPairedChar(editor, e)) {
                //tinymce.execCommand('ayahautocomplate',false,'وتد');
                return false;
              }

              endingMarkDowns(editor, e);
            });
            editor.on("keyup", function(e) {
              if (editor.selection) checkMarkDown(editor, e);

              //setingTag2(editor, e);
            });
            editor.on("keypress", function(e) {
              if (checkHalfSpace(editor, e)) {
                return false;
              } else if (checkNemayah(editor, e)) {
              } else if (wlast != "") {
                if ("js_AutoComplete" in window.external) {
                  window.external.js_AutoComplete(wlast, indexlast);
                }
              }
            });
            editor.on("change", function(e) {
              //console.log('Editor contents was changed.');
              if ("js_Changed" in window.external) {
                window.external.js_Changed("change");
              }
            });
            editor.on("redo", function(e) {
              //console.log('Editor contents was changed.');
              if ("js_Changed" in window.external) {
                window.external.js_Changed("redo");
              }
            });
            editor.on("undo", function(e) {
              //console.log('Editor contents was changed.');
              if ("js_Changed" in window.external) {
                window.external.js_Changed("undo");
              }
            });
            editor.ui.registry.addMenuItem("DeleteErab", {
              text: "Delete erab paragraph",
              context: "tools",
              shortcut: "Alt+5",
              onAction: function() {
                removeContentErab(editor);
              },
            });
            editor.ui.registry.addMenuItem("ParseHadith", {
              text: "Parse hadith format",
              context: "tools",
              shortcut: "Alt+6",
              onAction: function() {
                parseHadith(editor);
              },
            });

            // editor.ui.registry.addMenuItem('MenuTextOption', {
            // text: 'Text option',
            // context: 'tools',
            // getSubmenuItems: function () {
            // 	return [ {
            // 		text: "Delete erab",
            // 		onclick: function () {
            // 			removeContentErab(editor);
            // 		}
            // 		}, {
            // 			text: "Parse hadith format",
            // 			onclick: function () {
            // 				parseHadith(editor);
            // 			}
            // 		}]
            // 	}
            // });
          }
        },

        block_formats:
          "متن عادی=p; عنوان1=h1; عنوان 2=h2; عنوان 3=h3; عنوان 4=h4; عنوان 5=h5; عنوان 6=h6",
        plugins: [
          "advlist autolink lists link image imagetools charmap print preview anchor",
          "searchreplace visualblocks code fullscreen",
          "insertdatetime media table contextmenu paste imagetools wordcount autoresize searchreplace help quickbars",
        ],
        external_plugins: {
          hadithyab: "/tinymce/pluginsEx/hadithyab/plugin.min.js",
          tchecklist: "/tinymce/pluginsEx/tchecklist/plugin.min.js",
          comment: "/tinymce/pluginsEx/comment/plugin.min.js",
          footnotes: "/tinymce/pluginsEx/footnotes/plugin.min.js",
          ayahautocomplate: "/tinymce/pluginsEx/ayahautocomplate/plugin.min.js",
        },
        toolbar:
          "searchreplace undo redo copy paste | formatselect  styleselect | bold italic underline strikethrough | alignleft aligncenter 	alignright alignjustify | bullist numlist outdent indent | link image table | footnotes code hadithyab help",
        contextmenu:
          "copy paste pastetext removeformat | DeleteErab ParseHadith | footnotes link image",
        contextmenu_never_use_native: true,
        quickbars_insert_toolbar: false,
        //quickbars_insert_toolbar: 'quicktable image media codesample',
        quickbars_selection_toolbar:
          "bold underline | forecolor backcolor | bullist numlist | quicklink comment",
        style_formats: [
          { title: "آیه", inline: "span", classes: "tayah" },
          { title: "حدیث", inline: "span", classes: "thadith" },
          { title: "سند", inline: "span", classes: "tsanad" },
          { title: "اصطلاح", inline: "span", classes: "tterm" },
          { title: "برچسب", inline: "span", classes: "ttag" },
        ],
        paste_preprocess: function(plugin, args) {
          args.content = safePaste(args.content);
        },
        paste_postprocess: function(plugin, args) {
          //console.log(args.node);
          //args.node.setAttribute('id', '42');
        },
        paste_tab_spaces: 2,
        init_instance_callback: function(editor) {
          editor.shortcuts.add("alt+1", "درج علامت آیه", function() {
            tinymce.activeEditor.formatter.apply("ayah");
            unSelect(editor);
          }),
            editor.shortcuts.add("alt+2", "درج علامت حدیث", function() {
              tinymce.activeEditor.formatter.apply("hadith");
              unSelect(editor);
            }),
            editor.shortcuts.add("alt+3", "درج علامت سند", function() {
              tinymce.activeEditor.formatter.apply("sanad");
              unSelect(editor);
            }),
            editor.shortcuts.add("alt+4", "درج علامت اصطلاح", function() {
              tinymce.activeEditor.formatter.apply("term");
              unSelect(editor);
            }),
            editor.shortcuts.add("alt+5", "حذف اعراب متن جاری", function() {
              removeContentErab(editor);
            }),
            editor.shortcuts.add(
              "alt+6",
              "تحلیل خودکار سند و حدیث",
              function() {
                parseHadith(editor);
              }
            ),
            editor.shortcuts.add("f3", "درج علامت برچسب", function() {
              tinymce.activeEditor.formatter.apply("tag");
            }),
            editor.shortcuts.add("ctrl+alt+f", "درج پاورقی جدید", function() {
              tinymce.execCommand("footnotes", false, "");
            }),
            editor.shortcuts.add("ctrl+alt+c", "درج حاشیه جدید", function() {
              tinymce.execCommand("comment", false, "");
            });
        },

        formats: {
          alignleft: {
            selector: "p,h1,h2,h3,h4,h5,h6,td,th,div,ul,ol,li,table,img",
            classes: "left",
          },
          aligncenter: {
            selector: "p,h1,h2,h3,h4,h5,h6,td,th,div,ul,ol,li,table,img",
            classes: "center",
          },
          alignright: {
            selector: "p,h1,h2,h3,h4,h5,h6,td,th,div,ul,ol,li,table,img",
            classes: "right",
          },
          alignfull: {
            selector: "p,h1,h2,h3,h4,h5,h6,td,th,div,ul,ol,li,table,img",
            classes: "full",
          },
          bold: { inline: "span", classes: "tbold" },
          italic: { inline: "span", classes: "titalic" },
          underline: { inline: "span", classes: "tunderline", exact: true },
          strikethrough: { inline: "span", classes: "tstrikethrough" },
          ayah: { title: "آیه", inline: "span", classes: "tayah" },
          hadith: { title: "حدیث", inline: "span", classes: "thadith" },
          sanad: { title: "سند", inline: "span", classes: "tsanad" },
          term: { title: "اصطلاح", inline: "span", classes: "tterm" },
          tag: { title: "برچسب", inline: "span", classes: "ttag" },
        },
        content_css: "tinystyle.css",
        imagetools_toolbar:
          "rotateleft rotateright | flipv fliph | editimage imageoptions",

        //برای افزودن امکان درج تصویر از شخصی
        image_title: true,
        automatic_uploads: true,
        file_picker_types: "image",
        file_picker_callback: function(cb) {
          var input = document.createElement("input");
          input.setAttribute("type", "file");
          input.setAttribute("accept", "image/*");
          input.onchange = function() {
            var file = this.files[0];
            var reader = new FileReader();
            reader.onload = function() {
              var id = "blobid" + new Date().getTime();
              var blobCache = tinymce.activeEditor.editorUpload.blobCache;
              var base64 = reader.result.split(",")[1];
              var blobInfo = blobCache.create(id, file, base64);
              blobCache.add(blobInfo);
              cb(blobInfo.blobUri(), { title: file.name });
            };
            reader.readAsDataURL(file);
          };
          input.click();
        },

        content_style:
          "body { font-family:Sahel,Tahoma,Arial,sans-serif; font-size:16px }",
      },
    };
  },
  computed: {
    editorModel: {
      get() {
        return this.editorData;
      },
      set(value) {
        this.editorData = value;
      },
    },
  },
  methods: {
    save() {
      if (this.buttonLoading) return;
      this.buttonLoading = true;

      this.$emit("on-save", this.editorData);
    },
  },

};
</script>

<style></style>