import isEqual from 'lodash/isEqual';
import { BLOCK_TYPES, TEXT_EDITOR_DEFAULT_VALUE } from './text-editor-constants';

/**
 * @param {Array} value - the type of value is defined with TextEditorValue
 * @returns {boolean}
 */
export function isEmptyTextEditorValue(value) {
  return isEqual(value, TEXT_EDITOR_DEFAULT_VALUE);
}

/**
 * @param {Array} value - the type of value is defined with TextEditorValue
 * @param {number} maxLength
 * @returns {boolean}
 */
export function isLongerTextEditorValueThan(value, maxLength = 120) {
  let length = 0;
  for (const record of value) {
    // if we reached maxLength - no need to continue
    if (length > maxLength) {
      break;
    }
    // if this is leaf node that has text - sum it up
    if (record.hasOwnProperty('text') && !!record.text) {
      length += record?.text?.length ?? 0;
    } else if (record.hasOwnProperty('children') && !!record.children) {
      // if this is a node that has children - calculate length of children
      length += getTextEditorValueLength(record.children);
    }
  }
  return length > maxLength;
}
export function getTextEditorValueLength(value) {
  let length = 0;
  for (const record of value) {
    // if this is leaf node that has text - sum it up
    if (record.hasOwnProperty('text') && !!record.text) {
      length += record?.text?.length ?? 0;
    } else if (record.hasOwnProperty('children') && !!record.children) {
      // if this is a node that has children - iterate through them via recursion
      length += getTextEditorValueLength(record.children);
    }
  }
  return length;
}

/**
 * @param {Array} value - the type of value is defined with TextEditorValue
 * @param {number} maxTextLines
 * @returns {boolean}
 */
export function hasGreaterTextEditorLinesThan(value, maxTextLines = 1) {
  return value.length > maxTextLines;
}

/**
 * @param {string} text
 * @returns {Array.<object>} the type of value is defined with TextEditorValue
 */
export function convertTextToTextEditorValue(text) {
  return [{
    type: BLOCK_TYPES.REGULAR_TEXT,
    children: [{
      text
    }]
  }];
}