/**
 * @module tgam-patterns-text-resizer
 */

import EVENT_NAMES from "./event-names";
import ee from "./event-emitter";
import { toArray } from "./dom-methods";

let fontSizeIndex = 0;
let previousIndex = null;

/**
 * @method init
 * @description TODO
 * @param rootElement {HTMLElement}
 * @return {undefined}
 */
function init(rootElement) {
  let textResizers = toArray(rootElement.querySelectorAll(".c-control__button--text-resizer"));

  textResizers.forEach((el, index) => {
    el.addEventListener("click", this.onTextResizeClicked.bind(this, index));
  });

  ee.on(EVENT_NAMES.textResizer.textSizeChanged, onTextChanged);
}

/**
 * @method onTextResizeClicked
 * @description TODO
 * @param index {number}
 * @return {undefined}
 */
function onTextResizeClicked(index) {
  fontSizeIndex = index;

  ee.emit(EVENT_NAMES.textResizer.textSizeChanged, fontSizeIndex);
}

/**
 * @method onTextChanged
 * @description TODO
 * @param buttonIndex {number}
 * @return {undefined}
 */
function onTextChanged(buttonIndex) {
  const modifierClasses = ["", "c-text-resizer__body-text--plus-2", "c-text-resizer__body-text--plus-4", "c-text-resizer__body-text--plus-6"];
  const articleBody = document.querySelector(".c-text-resizer__body-text");

  previousIndex && articleBody.classList.remove(modifierClasses[previousIndex]);
  modifierClasses[buttonIndex] && articleBody.classList.add(modifierClasses[buttonIndex]);
  previousIndex = buttonIndex;
}

/////////////////////////////////////////
/////////////////////////////////////////
/////////////////////////////////////////

const textResizerObj = {};

textResizerObj.init = init;

textResizerObj.onTextResizeClicked = onTextResizeClicked;

textResizerObj.onTextChanged = onTextChanged;

export default textResizerObj;
