import convertToCSSPTValue, { PT_TO_PX_RATIO } from './convertToCSSPTValue.js';
import toHexColor from './ui/toHexColor.js';
export default function patchTableElements(doc) {
  Array.from(doc.querySelectorAll('td')).forEach(patchTableCell);
  Array.from(doc.querySelectorAll('tr[style^=height]')).forEach(patchTableRow);
}

// The height of each line: ~= 21px
var LINE_HEIGHT_PT_VALUE = 15.81149997;

// Workaround to patch HTML from Google Doc that Table Cells will apply
// its background colr to all its inner <span />.
function patchTableCell(tdElement) {
  var style = tdElement.style;
  if (!style) {
    return;
  }
  var backgroundColor = style.backgroundColor,
    width = style.width;
  if (backgroundColor) {
    var tdBgColor = toHexColor(backgroundColor);
    var selector = 'span[style*=background-color]';
    var spans = Array.from(tdElement.querySelectorAll(selector));
    spans.some(function (spanElement) {
      var retVal = true;
      var spanStyle = spanElement.style;
      if (!(spanStyle !== null && spanStyle !== void 0 && spanStyle.backgroundColor)) {
        retVal = false;
      } else {
        var spanBgColor = toHexColor(spanStyle.backgroundColor);
        if (spanBgColor === tdBgColor) {
          // The span has the same bg color as the cell does, erase its bg color.
          spanStyle.backgroundColor = '';
        }
      }
      return retVal;
    });
  }
  if (width) {
    var ptValue = convertToCSSPTValue(width);
    if (!ptValue) {
      return;
    }
    var pxValue = ptValue * PT_TO_PX_RATIO;
    // Attribute "data-colwidth" is defined at 'prosemirror-tables';
    tdElement.setAttribute('data-colwidth', String(Math.round(pxValue)));
  }
}

// Workaround to support "height" in table row by inject empty <p /> to
// create space for the height.
function patchTableRow(trElement) {
  var doc = trElement.ownerDocument;
  if (!doc) {
    return;
  }
  var height = trElement.style.height;
  if (!height) {
    return;
  }
  var firstCell = trElement.querySelector('td, th');
  if (!firstCell) {
    return;
  }
  var ptValue = convertToCSSPTValue(height);
  if (!ptValue) {
    return;
  }
  var pEls = firstCell.querySelectorAll('p');
  var heightNeeded = ptValue - LINE_HEIGHT_PT_VALUE * pEls.length;
  if (heightNeeded < 0) {
    return;
  }
  var pElsNeeded = Math.round(heightNeeded / LINE_HEIGHT_PT_VALUE);
  if (pElsNeeded <= 0) {
    return;
  }
  var frag = doc.createDocumentFragment();
  var line = doc.createElement('p');
  while (pElsNeeded > 0) {
    pElsNeeded--;
    frag.appendChild(line.cloneNode(false));
  }
  firstCell.appendChild(frag);
}