import {
  REGEXP,
  IMAGE_SPLIT,
  IMAGE_PROCESS_SMALL,
  IMAGE_PROCESS_LARGE,
  IMAGE_PROCESS
} from "./constant";
import emoji, { prefixUrl } from "./emoji";

const emojiObejct = arrayToObject(emoji, "title");

export function isFunction(functionToCheck) {
  return (
    functionToCheck && {}.toString.call(functionToCheck) === "[object Function]"
  );
}

export function isUrl(userInput) {
  // 需完整匹配
  const regexp = /^((http(s)?:)?\/\/.)?(www\.)?[-a-zA-Z0-9@:%._+~#=]{2,256}\.[a-z]{2,6}\b([-a-zA-Z0-9@:%_+.~#?&//=]*)/g;
  var res = userInput.match(regexp);
  if (res === null) return false;
  else return true;
}

/**
 * 将对象数组转换为对象
 * @param {array} array Array of Objects
 * @param {string} keyField string
 */
export function arrayToObject(array, keyField) {
  return array.reduce((obj, item) => {
    obj[item[keyField]] = item;
    return obj;
  }, {});
}

/**
 * HTML 编码
 * 将 < > 等字符串进行编码
 * @param {string} str 文本
 */
export function htmlEncode(str) {
  if (!str) return "";
  return str.replace(/[<>]/gim, function(i) {
    return "&#" + i.charCodeAt(0) + ";";
  });
}

/**
 * 渲染编辑器
 * [x] => <img src="x" />
 * @param {strig} content
 */
export function renderContent(content, onClick) {
  let newContent = content;
  if (newContent.indexOf(IMAGE_SPLIT) !== -1) {
    newContent = newContent.split(IMAGE_SPLIT);
    newContent.pop();
    newContent = newContent.join("");
  }
  // 不包含在标签内的链接
  const innerUrl = /((http(s)?:)?\/\/)?(www\.)?[-a-zA-Z0-9@:%._+~#=]{2,256}\.[a-z]{2,6}\b([-a-zA-Z0-9@:%_+.~#?&//=]*)(?![^<>]*>|[^"]*?<\/a)/g;
  const data = htmlEncode(newContent)
    .replace(REGEXP, function(a, b) {
      const src = a.slice(1, -1);

      // 兼容旧的评
      // 因为旧的评论用 [img url] 方式存储的
      if (isUrl(src)) {
        return `<a href="${src}" rel="noopener noreferrer" target="_blank"><img class="comment-img" src="${src}" alt="${src}" /></a>`;
      }
      // 如果不存在对应的表情, 则返回原文
      const emoji = emojiObejct[src];
      if (emoji) {
        return `<img class="comment-emoji" src="${prefixUrl}${emoji.value}.${
          emoji.ext
        }" alt="${emoji.title}" />`;
      }
      return `[${src}]`;
    })
    .replace(innerUrl, function(a, b) {
      const protocol = /^(https?:)?\/\//;
      const hasProtocol = protocol.test(a);
      const url = hasProtocol ? a : `//${a}`;
      // target="_blank" 存在安全性问题
      // return `<a href="${url}" target="_blank" rel="noopener noreferrer" >${a}</a>`;
      return `<a href="${url}">${a}</a>`;
    })
    .replace(/\n/g, "<br />");
  return data;
}

export function addImageProcess(url, options = {}) {
  if (options.small) {
    return url + IMAGE_PROCESS_SMALL;
  }
  if (options.large) {
    return url + IMAGE_PROCESS_LARGE;
  }
  return url + IMAGE_PROCESS;
}
