/**
 * Copyright (c) Tiny Technologies, Inc. All rights reserved.
 * Licensed under the LGPL or a commercial license.
 * For LGPL see License.txt in the project root for license information.
 * For commercial licenses see https://www.tiny.cloud/
 */

import { Node, Text } from '@ephox/dom-globals';

const isTextNode = function (node: Node): node is Text {
  return node && node.nodeType === 3;
};

const isListNode = function (node: Node) {
  return node && (/^(OL|UL|DL)$/).test(node.nodeName);
};

const isOlUlNode = function (node: Node) {
  return node && (/^(OL|UL)$/).test(node.nodeName);
};

const isListItemNode = function (node: Node) {
  return node && /^(LI|DT|DD)$/.test(node.nodeName);
};

const isDlItemNode = function (node: Node) {
  return node && /^(DT|DD)$/.test(node.nodeName);
};

const isTableCellNode = function (node: Node) {
  return node && /^(TH|TD)$/.test(node.nodeName);
};

const isBr = function (node: Node) {
  return node && node.nodeName === 'BR';
};

const isFirstChild = function (node: Node) {
  return node.parentNode.firstChild === node;
};

const isLastChild = function (node: Node) {
  return node.parentNode.lastChild === node;
};

const isTextBlock = function (editor, node: Node) {
  return node && !!editor.schema.getTextBlockElements()[node.nodeName];
};

const isBlock = function (node: Node, blockElements) {
  return node && node.nodeName in blockElements;
};

const isBogusBr = function (dom, node: Node) {
  if (!isBr(node)) {
    return false;
  }

  if (dom.isBlock(node.nextSibling) && !isBr(node.previousSibling)) {
    return true;
  }

  return false;
};

const isEmpty = function (dom, elm, keepBookmarks?) {
  const empty = dom.isEmpty(elm);

  if (keepBookmarks && dom.select('span[data-mce-type=bookmark]', elm).length > 0) {
    return false;
  }

  return empty;
};

const isChildOfBody = function (dom, elm) {
  return dom.isChildOf(elm, dom.getRoot());
};

export {
  isTextNode,
  isListNode,
  isOlUlNode,
  isDlItemNode,
  isListItemNode,
  isTableCellNode,
  isBr,
  isFirstChild,
  isLastChild,
  isTextBlock,
  isBlock,
  isBogusBr,
  isEmpty,
  isChildOfBody
};
