/**
 * 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 DOMUtils from 'tinymce/core/api/dom/DOMUtils';
import Tools from 'tinymce/core/api/util/Tools';
import * as NodeType from './NodeType';

const DOM = DOMUtils.DOM;

const normalizeList = (dom, ul) => {
  let sibling;
  const parentNode = ul.parentNode;

  // Move UL/OL to previous LI if it's the only child of a LI
  if (parentNode.nodeName === 'LI' && parentNode.firstChild === ul) {
    sibling = parentNode.previousSibling;
    if (sibling && sibling.nodeName === 'LI') {
      sibling.appendChild(ul);

      if (NodeType.isEmpty(dom, parentNode)) {
        DOM.remove(parentNode);
      }
    } else {
      DOM.setStyle(parentNode, 'listStyleType', 'none');
    }
  }

  // Append OL/UL to previous LI if it's in a parent OL/UL i.e. old HTML4
  if (NodeType.isListNode(parentNode)) {
    sibling = parentNode.previousSibling;
    if (sibling && sibling.nodeName === 'LI') {
      sibling.appendChild(ul);
    }
  }
};

const normalizeLists = (dom, element) => {
  Tools.each(Tools.grep(dom.select('ol,ul', element)), (ul) => {
    normalizeList(dom, ul);
  });
};

export {
  normalizeList,
  normalizeLists
};
