//@ts-check

import { percentFromProgress } from "./percentFromProgress.mjs";

/**
 * Returns a function that can update an HTML Element.
 * The function, when called with `received` and `total`, set 3 custom css vars
 * on the element, which can be used in CSS to reflect the state of the object
 * @param {HTMLElement} element
 */
export const trackProgressWithCSS = (element, prefix = "load-") => {
  const keyFract = `--${prefix}fraction`;
  const keyProgress = `--${prefix}progress`;
  const keyProgressStr = `--${prefix}progress-str`;
  const classComplete = `${prefix}complete`;
  /**
   * @param {{received: number, total: number}} progress
   */
  const setProgress = ({ received, total }) => {
    const final = received == total;
    const fraction = final ? 1 : received / total;
    const percent = final ? "100%" : percentFromProgress(fraction, true);
    console.log(keyProgress, percent);
    element.style.setProperty(keyFract, `${fraction}`);
    element.style.setProperty(keyProgress, percent);
    element.style.setProperty(keyProgressStr, `"${percent}"`);
    if (final) {
      console.log("all done!", element, classComplete)
      requestAnimationFrame(() => element.classList.add(classComplete));
    }
  };
  return setProgress;
};

export default trackProgressWithCSS;
