/**
 * Applies attributes based on the user's current Discord user settings.
 * @module Settings
 * @memberof Builtin.Attributes.Misc
 */

import { getModule, FluxDispatcher } from '@vizality/webpack';

export const labels = [ 'Misc', 'Settings' ];

export default () => {
  const root = document?.documentElement;
  const setAttribute = (setting, value) => {
    root?.setAttribute(`vz-${setting}`, value);
  };

  /**
   * Handles when a Discord user settings change is triggered.
   * @param {object} settings Discord user settings
   */
  const handleSettingsChange = ({ settings }) => {
    if (settings?.theme) {
      setAttribute('theme', settings.theme);
    }
    /*
     * We're checking explicitly for true and false values here.
     */
    if (settings?.messageDisplayCompact === true) {
      setAttribute('mode', 'compact');
    } else if (settings?.messageDisplayCompact === false) {
      setAttribute('mode', 'cozy');
    }
  };

  /*
   * Set up the Discord settings attributes we want initially.
   */
  handleSettingsChange(getModule('locale', 'theme'));

  /**
   * Subscribe to Discord's user settings uppdate flux store.
   */
  FluxDispatcher?.subscribe($discord.constants.ActionTypes.USER_SETTINGS_UPDATE, handleSettingsChange);

  /**
   * Remove attributes and unsubscribe from Flux on unload.
   */
  return () => {
    root?.removeAttribute('vz-theme');
    root?.removeAttribute('vz-mode');
    FluxDispatcher?.unsubscribe($discord.constants.ActionTypes.USER_SETTINGS_UPDATE, handleSettingsChange);
  };
};
