/**
 * Utility helpers for scaling PIXI Text instances within attachments.
 */
export const TextHelper = {
  /**
   * Fits the provided text display object into the supplied bounding box.
   * @param {import('pixi.js').Text} textObject Text display instance to scale.
   * @param {{width: number, height: number}} size Bounding box dimensions.
   */
  scaleToFit(textObject, size) {
    textObject.scale.set(1);

    if (textObject.style?.wordWrap) {
      if (!textObject.style.defaultWordWrapWidth) {
        textObject.style.defaultWordWrapWidth = textObject.style.wordWrapWidth;
      }

      textObject.style.wordWrapWidth = textObject.style.defaultWordWrapWidth;
      const scaleStep = 0.99;

      while (size.width / textObject.width < 1 || size.height / textObject.height < 1) {
        textObject.scale.set(textObject.scale.x * scaleStep, textObject.scale.y * scaleStep);
        textObject.style.wordWrapWidth /= scaleStep;
      }

      return;
    }

    const factor = Math.min(1, size.width / textObject.width, size.height / textObject.height);
    textObject.scale.set(factor);
  }
};
