import { AUDIO_IMG_URL } from "./constants";

/**
 *
 * @param {HTMLDivElement} editor 要操作的编辑器dom，还未想好怎么用
 * @param {String} tagName IMG | AUDIO
 * @param {String} value 相对于本地电脑资源的路径
 */
export function insertTagToEditor(editor, tagName, value, attributes = {}) {
  let sel, range;
  if (window.getSelection) {
    sel = window.getSelection();
    if (sel.getRangeAt && sel.rangeCount) {
      range = sel.getRangeAt(0);
      range.deleteContents();

      // TODO:
      // if (tagName === "AUDIO") {
      //   const el = document.createElement("audio");
      //   el.src = value;
      //   el.className = "audio";
      //   // el.style = "height: 18px; width: 180px;";
      //   el.controls = true;
      //   el.controlsList = "nodownload";
      //   // el.draggable = true;
      //   range.insertNode(el);
      // }
      if (tagName === "IMG") {
        const el = document.createElement("img");
        // console.log(value);
        el.src = value;
        el.dataset.isImage = true;
        if (Object.keys(attributes).length) {
          Object.keys(attributes).forEach((k) => {
            el.setAttribute(k, attributes[k]);
          });
        }
        range.insertNode(el);
        range.collapse();
      }
      editor && editor.dispatchEvent(new Event("input"));
    }
  }
}

/**
 * 将音频路径转换为图片占位符
 *
 * @param {aduioSrc} value 相对于本地电脑资源的路径
 * @returns {HTMLImageElement} 图片节点
 */
export async function audioToImageNode(audioSrc) {
  const duration = 1;

  const el = document.createElement("img");
  el.src = AUDIO_IMG_URL;
  el.dataset.isAudio = true;
  el.dataset.audioSrc = audioSrc;
  el.dataset.duration = duration;
  const mDuration = require("moment").unix(0);
  mDuration.second(duration);
  el.title = mDuration.format("mm:ss");

  el.className = "audio";

  return el;
}

/**
 * 获取答题点序号图片base64
 * @param {number} serialNo 答题点序号
 * @returns dataUrl
 */
export function getAnswerPointImg(serialNo) {
  const canvas = document.createElement("canvas");
  const ctx = canvas.getContext("2d");
  canvas.width = 64;
  canvas.height = 32;
  ctx.font = "bolder 30px serif";
  ctx.textAlign = "center";
  ctx.textBaseline = "middle";
  ctx.fillText(`（${serialNo}）`, 32, 16);
  return canvas.toDataURL();
}

export function base64ToBlob(base64Str) {
  var bytes = atob(base64Str.split(",")[1]);
  let arr = new Uint8Array(bytes.length);
  for (let i = 0; i < bytes.length; i++) {
    arr[i] = bytes.charCodeAt(i);
  }
  return new Blob([arr], { type: "image/png" });
}
